Ejemplo n.º 1
0
        public async static Task<LoginResult> SignInAsync(LoginUserInfo loginUserInfo)
        {
            try
            {
                string data = JsonSerializeHelper.Serialize(loginUserInfo);
                var content = new StringContent(data, Encoding.UTF8, Constants.JsonMediaType);

                Uri uri = new Uri(WcfApiUrlConstants.LoginUrl);
                content.Headers.Add(Constants.XRequestWith, Constants.XmlHttpRequest);
                content.Headers.Add(Constants.VerificationToken, loginUserInfo.VerificationToken);
                HttpHelper.HttpClientHandler.CookieContainer.Add(uri, new Cookie(Constants.ServerId, loginUserInfo.ServerId));
                HttpHelper.HttpClientHandler.CookieContainer.Add(uri, new Cookie(Constants.AspxAutoDetectCookieSupport, "1"));
                var response = await HttpHelper.HttpClient.PostAsync(uri, content);
                response.EnsureSuccessStatusCode();
                string responseContent = await response.Content.ReadAsStringAsync();
                LoginResult postResult = JsonSerializeHelper.Deserialize<LoginResult>(responseContent);
                if (postResult.Success)// || postResult.Message == Constants.HadLogined)//提示已登录过cnblogs不能从响应中获取cookie。
                {
                    Cookie cookie = HttpHelper.LoadCookieFromHeader(response.Headers, Constants.AuthenticationCookiesName);
                    HttpHelper.HttpClientHandler.CookieContainer.Add(uri, cookie);
                    //登录成功先保存cookie
                    CacheManager.Current.UpdateCookies(cookie);
                }
                return postResult;
            }
            catch(Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return new LoginResult() { Success = false, Message = exception.Message };
            }
        }
Ejemplo n.º 2
0
 public void Load()
 {
     ApplicationDataCompositeValue composite;
     LoginUserInfo = new LoginUserInfo();
     //获取用户登录信息
     if (_setting.GetSetting(nameof(LoginUserInfo), out composite))
     {
         //存在缓存
         LoginUserInfo.UserName = (string)composite[nameof(LoginUserInfo.UserName)];
         LoginUserInfo.Password = (string)composite[nameof(LoginUserInfo.Password)];
         LoginUserInfo.Blogger.Guid = (string)composite[nameof(LoginUserInfo.Blogger.Guid)];
         LoginUserInfo.Blogger.BlogApp = (string)composite[nameof(LoginUserInfo.Blogger.BlogApp)];
         ApplicationDataCompositeValue cookiesComposite;
         //存在cookies则获取
         if (_setting.GetSetting(nameof(LoginUserInfo.Cookies), out cookiesComposite))
         {
             foreach (string key in cookiesComposite.Keys)
             {
                 var cookie = new Cookie(key, (string)cookiesComposite[key],"/", Constants.Domain);
                 LoginUserInfo.Cookies.Add(cookie);
                 HttpHelper.AddCookies(new Uri(Constants.Host), cookie);
             }
         }
     }
 }
Ejemplo n.º 3
0
 public async static Task<byte[]> LoadValidateImage(LoginUserInfo loginUserInfo)
 {
     //获取验证码实例ID
     //uri.Query,t=f8d90cc2aa2d4972bd2f1e46ae61364a
     loginUserInfo.CaptchaInstanceId = loginUserInfo.ImageSrc.Substring(loginUserInfo.ImageSrc.IndexOf(";t=") + 3);
     return await HttpHelper.HttpClient.GetByteArrayAsync(WcfApiUrlConstants.BaseLoginUrl + loginUserInfo.ImageSrc);
 }
Ejemplo n.º 4
0
 public async static Task InitLoginUserInfo(LoginUserInfo loginUserInfo)
 {
     Uri uri = new Uri(WcfApiUrlConstants.LoginUrl);
     //先请求一次获取cookies
     var response = await HttpHelper.HttpClient.GetAsync(uri);
     string html = await response.Content.ReadAsStringAsync();
     if (loginUserInfo.VerificationToken.IsNullOrEmpty())
     {
         //LoginCaptcha_CaptchaImage 验证码 获取 src
         Match match = Regex.Match(html, Constants.GetImageSrc);
         if (match.Success)
         {
             loginUserInfo.ImageSrc = match.Groups[Constants.Url].Value;
         }
         match = Regex.Match(html, Constants.FindVerificationTokenRegexString);
         if (match.Success)
         {
             loginUserInfo.VerificationToken = match.Groups[1].Value;
         }
     }
     Cookie serverId = HttpHelper.LoadCookieFromHeader(response.Headers, Constants.ServerId);
     loginUserInfo.ServerId = serverId.Value;
 }
Ejemplo n.º 5
0
        public async Task <IActionResult> Login([FromForm] string userid, [FromForm] string password, [FromForm] bool rememberLogin = false, [FromForm] bool cookie = true)
        {
            var user = DC.Set <FrameworkUserBase>()
                       .Include(x => x.UserRoles)
                       .Include(x => x.UserGroups)
                       .Where(x => x.ITCode.ToLower() == userid.ToLower() && x.Password == Utils.GetMD5String(password) && x.IsValid)
                       .SingleOrDefault();

            //如果没有找到则输出错误
            if (user == null)
            {
                return(BadRequest("LoadFailed"));
            }
            var roleIDs  = user.UserRoles.Select(x => x.RoleId).ToList();
            var groupIDs = user.UserGroups.Select(x => x.GroupId).ToList();
            //查找登录用户的数据权限
            var dpris = DC.Set <DataPrivilege>()
                        .Where(x => x.UserId == user.ID || (x.GroupId != null && groupIDs.Contains(x.GroupId.Value)))
                        .ToList();

            ProcessTreeDp(dpris);
            //生成并返回登录用户信息
            var rv = new LoginUserInfo();

            rv.Id             = user.ID;
            rv.ITCode         = user.ITCode;
            rv.Name           = user.Name;
            rv.Roles          = DC.Set <FrameworkRole>().Where(x => user.UserRoles.Select(y => y.RoleId).Contains(x.ID)).ToList();
            rv.Groups         = DC.Set <FrameworkGroup>().Where(x => user.UserGroups.Select(y => y.GroupId).Contains(x.ID)).ToList();
            rv.DataPrivileges = dpris;
            //查找登录用户的页面权限
            var pris = DC.Set <FunctionPrivilege>()
                       .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                       .ToList();

            rv.FunctionPrivileges = pris;
            rv.PhotoId            = user.PhotoId;
            LoginUserInfo         = rv;

            if (cookie) // cookie auth
            {
                AuthenticationProperties properties = null;
                if (rememberLogin)
                {
                    properties = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                    };
                }

                var principal = LoginUserInfo.CreatePrincipal();
                // 在上面注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

                List <SimpleMenu> ms     = new List <SimpleMenu>();
                LoginUserInfo     forapi = new LoginUserInfo();
                forapi.Id      = LoginUserInfo.Id;
                forapi.ITCode  = LoginUserInfo.ITCode;
                forapi.Name    = LoginUserInfo.Name;
                forapi.Roles   = LoginUserInfo.Roles;
                forapi.Groups  = LoginUserInfo.Groups;
                forapi.PhotoId = LoginUserInfo.PhotoId;
                var menus = DC.Set <FunctionPrivilege>()
                            .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                            .Select(x => x.MenuItem)
                            .Where(x => x.MethodName == null)
                            .OrderBy(x => x.DisplayOrder)
                            .Select(x => new SimpleMenu
                {
                    Id       = x.ID.ToString().ToLower(),
                    ParentId = x.ParentId.ToString().ToLower(),
                    Text     = x.PageName,
                    Url      = x.Url,
                    Icon     = x.ICon
                });
                ms.AddRange(menus);

                List <string> urls = new List <string>();
                urls.AddRange(DC.Set <FunctionPrivilege>()
                              .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                              .Select(x => x.MenuItem)
                              .Where(x => x.MethodName != null)
                              .Select(x => x.Url)
                              );
                urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
                forapi.Attributes = new Dictionary <string, object>();
                forapi.Attributes.Add("Menus", menus);
                forapi.Attributes.Add("Actions", urls);

                return(Ok(forapi));
            }
            else // jwt auth
            {
                var authService = HttpContext.RequestServices.GetService(typeof(ITokenService)) as ITokenService;

                var token = await authService.IssueTokenAsync(LoginUserInfo);

                return(Content(JsonConvert.SerializeObject(token), "application/json"));
            }
        }
        public void Create()
        {
            UserInfo userInfo = LoginUserInfo.Get();

            appid = userInfo.companyId;
        }
Ejemplo n.º 7
0
        public IActionResult Login([FromForm] string userid, [FromForm] string password)
        {
            var user = DC.Set <FrameworkUserBase>()
                       .Include(x => x.UserRoles).Include(x => x.UserGroups)
                       .Where(x => x.ITCode.ToLower() == userid.ToLower() && x.Password == Utils.GetMD5String(password) && x.IsValid)
                       .SingleOrDefault();

            //如果没有找到则输出错误
            if (user == null)
            {
                ModelState.AddModelError(" login", "登录失败");
                return(BadRequest(ModelState.GetErrorJson()));
            }
            var roleIDs  = user.UserRoles.Select(x => x.RoleId).ToList();
            var groupIDs = user.UserGroups.Select(x => x.GroupId).ToList();
            //查找登录用户的数据权限
            var dpris = DC.Set <DataPrivilege>()
                        .Where(x => x.UserId == user.ID || (x.GroupId != null && groupIDs.Contains(x.GroupId.Value)))
                        .ToList();
            //生成并返回登录用户信息
            LoginUserInfo rv = new LoginUserInfo();

            rv.Id             = user.ID;
            rv.ITCode         = user.ITCode;
            rv.Name           = user.Name;
            rv.Roles          = DC.Set <FrameworkRole>().Where(x => user.UserRoles.Select(y => y.RoleId).Contains(x.ID)).ToList();
            rv.Groups         = DC.Set <FrameworkGroup>().Where(x => user.UserGroups.Select(y => y.GroupId).Contains(x.ID)).ToList();
            rv.DataPrivileges = dpris;
            rv.PhotoId        = user.PhotoId;
            //查找登录用户的页面权限
            var pris = DC.Set <FunctionPrivilege>()
                       .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                       .ToList();

            rv.FunctionPrivileges = pris;
            LoginUserInfo         = rv;

            LoginUserInfo forapi = new LoginUserInfo();

            forapi.Id      = user.ID;
            forapi.ITCode  = user.ITCode;
            forapi.Name    = user.Name;
            forapi.Roles   = rv.Roles;
            forapi.Groups  = rv.Groups;
            forapi.PhotoId = rv.PhotoId;
            List <SimpleMenu> ms = new List <SimpleMenu>();

            var menus = DC.Set <FunctionPrivilege>()
                        .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                        .Select(x => x.MenuItem)
                        .Where(x => x.MethodName == null)
                        .OrderBy(x => x.DisplayOrder)
                        .Select(x => new SimpleMenu
            {
                Id       = x.ID.ToString().ToLower(),
                ParentId = x.ParentId.ToString().ToLower(),
                Text     = x.PageName,
                Url      = x.Url,
                Icon     = x.ICon
            });

            var folders = DC.Set <FrameworkMenu>().Where(x => x.FolderOnly == true).Select(x => new SimpleMenu
            {
                Id       = x.ID.ToString().ToLower(),
                ParentId = x.ParentId.ToString().ToLower(),
                Text     = x.PageName,
                Url      = x.Url,
                Icon     = x.ICon
            });

            ms.AddRange(folders);
            foreach (var item in menus)
            {
                if (folders.Any(x => x.Id == item.Id) == false)
                {
                    ms.Add(item);
                }
            }

            List <string> urls = new List <string>();

            urls.AddRange(DC.Set <FunctionPrivilege>()
                          .Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                          .Select(x => x.MenuItem)
                          .Where(x => x.MethodName != null)
                          .Select(x => x.Url)
                          );
            urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
            forapi.Attributes = new Dictionary <string, object>();
            forapi.Attributes.Add("Menus", ms);
            forapi.Attributes.Add("Actions", urls);
            return(Ok(forapi));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取文件的历史信息
        /// </summary>
        /// <param name="fileInfoId">主键</param>
        /// <returns></returns>
        public IEnumerable <FileBInfoEntity> GetHistoryList(string fileInfoId)
        {
            List <FileBInfoEntity> list = new List <FileBInfoEntity>();


            var strSql = new StringBuilder();

            strSql.Append(" select t.*,t1.F_Ver,t1.F_FileId,t1.F_PFiled,t3.F_FileSize,t3.F_FileType,1 as Type,'1,3' as F_AuthType from lr_base_fileinfo t ");
            strSql.Append(" LEFT JOIN lr_base_filelist t1 on t1.F_FileInfoId = t.F_Id ");
            strSql.Append(" LEFT JOIN LR_Base_AnnexesFile t3 on t3.F_FolderId = t1.F_FileId ");
            strSql.Append(" where t.F_IsPublish = 1 AND t.F_Id = @fileInfoId  order by t1.F_PublishTime DESC ");

            list.AddRange(this.BaseRepository().FindList <FileBInfoEntity>(strSql.ToString(), new { fileInfoId }));

            UserInfo userInfo = LoginUserInfo.Get();

            if (!userInfo.isSystem)
            {
                string roleIds = userInfo.roleIds;
                if (string.IsNullOrEmpty(roleIds))
                {
                    return(list);
                }
                else
                {
                    roleIds = "('" + roleIds.Replace(",", "','") + "')";

                    var authList = (List <FileAuthEntity>) this.BaseRepository().FindList <FileAuthEntity>(" select * from lr_base_fileauth where F_ObjId in " + roleIds + " AND  F_Time >= @ftime  ORDER BY F_Level ", new { ftime = DateTime.Now });


                    List <FileBInfoEntity> list2 = new List <FileBInfoEntity>();

                    foreach (var item in list)
                    {
                        var  roleIdList = userInfo.roleIds.Split(',');
                        bool flag       = false;
                        item.F_AuthType = "";
                        foreach (var roleIdItem in roleIdList)
                        {
                            var authList2 = authList.FindAll(t => t.F_FileInfoId == item.F_Id && t.F_ObjId == roleIdItem);
                            if (authList2.Count > 0)
                            {
                                flag = true;
                                if (item.F_AuthType != "")
                                {
                                    item.F_AuthType += ",";
                                }
                                item.F_AuthType += authList2[0].F_AuthType;
                            }
                        }

                        if (flag)
                        {
                            list2.Add(item);
                        }
                    }

                    return(list2);
                }
            }
            return(list);
        }
Ejemplo n.º 9
0
        public ActionResult Auditer(bool isNew, string processId, string schemeCode, string taskId, string formData)
        {
            WfParameter wfParameter = new WfParameter();
            UserInfo    userInfo    = LoginUserInfo.Get();

            wfParameter.companyId    = userInfo.companyId;
            wfParameter.departmentId = userInfo.departmentId;
            wfParameter.userId       = userInfo.userId;
            wfParameter.userName     = userInfo.realName;
            wfParameter.isNew        = isNew;
            wfParameter.processId    = processId;
            wfParameter.schemeCode   = schemeCode;
            wfParameter.taskId       = taskId;
            wfParameter.formData     = formData;

            WfResult <List <object> > res = wfEngineIBLL.GetAuditer(wfParameter);

            if (res.status == 1)
            {
                List <object> nodelist = new List <object>();
                var           list     = res.data;
                foreach (var item1 in list)
                {
                    var item = item1.ToJson().ToJObject();
                    if (item["auditors"].IsEmpty())
                    {
                        var point = new
                        {
                            all    = true,
                            name   = item["name"],
                            nodeId = item["nodeId"]
                        };
                        nodelist.Add(point);
                    }
                    else
                    {
                        List <object> userlist = new List <object>();
                        foreach (var auditor in item["auditors"])
                        {
                            switch (auditor["type"].ToString())  //获取人员信息1.岗位2.角色3.用户
                            {
                            case "1":
                            case "2":
                                var    userRelationList = userRelationIBLL.GetUserIdList(auditor["auditorId"].ToString());
                                string userIds          = "";
                                foreach (var userRelation in userRelationList)
                                {
                                    if (userIds != "")
                                    {
                                        userIds += ",";
                                    }
                                    userIds += userRelation.F_UserId;
                                }
                                var userList = userIBLL.GetListByUserIds(userIds);
                                if (userList != null)
                                {
                                    foreach (var user in userList)
                                    {
                                        if (user != null)
                                        {
                                            userlist.Add(new { id = user.F_UserId, name = user.F_RealName });
                                        }
                                    }
                                }
                                break;

                            case "3":
                                userlist.Add(new { id = auditor["auditorId"], name = auditor["auditorName"] });
                                break;
                            }
                        }
                        var point = new
                        {
                            name   = item["name"],
                            nodeId = item["nodeId"],
                            list   = userlist
                        };
                        nodelist.Add(point);
                    }
                }

                return(Success(nodelist));
            }
            else
            {
                return(Fail("获取数据失败!"));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获得指定模块或者编号的单据号
        /// </summary>
        /// <param name="enCode">编码</param>
        /// <param name="userId">用户ID</param>
        /// <returns>单据号</returns>
        public string GetBillCode(string enCode, string userId = "")
        {
            try
            {
                string billCode     = "";    //单据号
                string nextBillCode = "";    //单据号
                bool   isOutTime    = false; //是否已过期


                CodeRuleEntity coderuleentity = GetEntityByCode(enCode);
                if (coderuleentity != null)
                {
                    UserInfo userInfo = null;
                    if (string.IsNullOrEmpty(userId))
                    {
                        userInfo = LoginUserInfo.Get();
                    }
                    else
                    {
                        UserEntity userEntity = userIBLL.GetEntityByUserId(userId);
                        userInfo = new UserInfo
                        {
                            userId       = userEntity.F_UserId,
                            enCode       = userEntity.F_EnCode,
                            password     = userEntity.F_Password,
                            secretkey    = userEntity.F_Secretkey,
                            realName     = userEntity.F_RealName,
                            nickName     = userEntity.F_NickName,
                            headIcon     = userEntity.F_HeadIcon,
                            gender       = userEntity.F_Gender,
                            mobile       = userEntity.F_Mobile,
                            telephone    = userEntity.F_Telephone,
                            email        = userEntity.F_Email,
                            oICQ         = userEntity.F_OICQ,
                            weChat       = userEntity.F_WeChat,
                            companyId    = userEntity.F_CompanyId,
                            departmentId = userEntity.F_DepartmentId,
                            openId       = userEntity.F_OpenId,
                            isSystem     = userEntity.F_SecurityLevel == 1 ? true : false
                        };
                    }

                    int nowSerious = 0;
                    List <CodeRuleFormatModel> codeRuleFormatList = coderuleentity.F_RuleFormatJson.ToList <CodeRuleFormatModel>();
                    string dateFormatStr = "";
                    foreach (CodeRuleFormatModel codeRuleFormatEntity in codeRuleFormatList)
                    {
                        switch (codeRuleFormatEntity.itemType.ToString())
                        {
                        //自定义项
                        case "0":
                            billCode     = billCode + codeRuleFormatEntity.formatStr;
                            nextBillCode = nextBillCode + codeRuleFormatEntity.formatStr;
                            break;

                        //日期
                        case "1":
                            //日期字符串类型
                            dateFormatStr = codeRuleFormatEntity.formatStr;
                            billCode      = billCode + DateTime.Now.ToString(codeRuleFormatEntity.formatStr.Replace("m", "M"));
                            nextBillCode  = nextBillCode + DateTime.Now.ToString(codeRuleFormatEntity.formatStr.Replace("m", "M"));
                            break;

                        //流水号
                        case "2":
                            CodeRuleSeedEntity        maxSeed            = null;
                            CodeRuleSeedEntity        codeRuleSeedEntity = null;
                            List <CodeRuleSeedEntity> seedList           = GetSeedList(coderuleentity.F_RuleId, userInfo);
                            maxSeed = seedList.Find(t => t.F_UserId.IsEmpty());
                            #region 处理流水号归0
                            // 首先确定最大种子是否未归0的
                            if (dateFormatStr.Contains("dd"))
                            {
                                if ((maxSeed.F_ModifyDate).ToDateString() != DateTime.Now.ToString("yyyy-MM-dd"))
                                {
                                    isOutTime            = true;
                                    nowSerious           = 1;
                                    maxSeed.F_SeedValue  = 2;
                                    maxSeed.F_ModifyDate = DateTime.Now;
                                }
                            }
                            else if (dateFormatStr.Contains("mm"))
                            {
                                if (((DateTime)maxSeed.F_ModifyDate).ToString("yyyy-MM") != DateTime.Now.ToString("yyyy-MM"))
                                {
                                    isOutTime            = true;
                                    nowSerious           = 1;
                                    maxSeed.F_SeedValue  = 2;
                                    maxSeed.F_ModifyDate = DateTime.Now;
                                }
                            }
                            else if (dateFormatStr.Contains("yy"))
                            {
                                if (((DateTime)maxSeed.F_ModifyDate).ToString("yyyy") != DateTime.Now.ToString("yyyy"))
                                {
                                    isOutTime            = true;
                                    nowSerious           = 1;
                                    maxSeed.F_SeedValue  = 2;
                                    maxSeed.F_ModifyDate = DateTime.Now;
                                }
                            }
                            #endregion
                            // 查找当前用户是否已有之前未用掉的种子做更新
                            codeRuleSeedEntity = seedList.Find(t => t.F_UserId == userInfo.userId && t.F_RuleId == coderuleentity.F_RuleId && (t.F_CreateDate).ToDateString() == DateTime.Now.ToString("yyyy-MM-dd"));
                            string keyvalue = codeRuleSeedEntity == null ? "" : codeRuleSeedEntity.F_RuleSeedId;
                            if (isOutTime)
                            {
                                SaveSeed(maxSeed.F_RuleSeedId, maxSeed, userInfo);
                            }
                            else if (codeRuleSeedEntity == null)
                            {
                                nowSerious           = (int)maxSeed.F_SeedValue;
                                maxSeed.F_SeedValue += 1;
                                maxSeed.Modify(maxSeed.F_RuleSeedId, userInfo);
                                SaveSeed(maxSeed.F_RuleSeedId, maxSeed, userInfo);
                            }
                            else
                            {
                                nowSerious = (int)codeRuleSeedEntity.F_SeedValue;
                            }

                            codeRuleSeedEntity = new CodeRuleSeedEntity();
                            codeRuleSeedEntity.Create(userInfo);
                            codeRuleSeedEntity.F_SeedValue = nowSerious;
                            codeRuleSeedEntity.F_UserId    = userInfo.userId;
                            codeRuleSeedEntity.F_RuleId    = coderuleentity.F_RuleId;
                            SaveSeed(keyvalue, codeRuleSeedEntity, userInfo);
                            // 最大种子已经过期
                            string seriousStr     = new string('0', (int)(codeRuleFormatEntity.formatStr.Length - nowSerious.ToString().Length)) + nowSerious.ToString();
                            string NextSeriousStr = new string('0', (int)(codeRuleFormatEntity.formatStr.Length - nowSerious.ToString().Length)) + maxSeed.F_SeedValue.ToString();
                            billCode     = billCode + seriousStr;
                            nextBillCode = nextBillCode + NextSeriousStr;
                            break;

                        //部门
                        case "3":
                            DepartmentEntity departmentEntity = departmentIBLL.GetEntity(userInfo.companyId, userInfo.departmentId);
                            if (codeRuleFormatEntity.formatStr == "code")
                            {
                                billCode     = billCode + departmentEntity.F_EnCode;
                                nextBillCode = nextBillCode + departmentEntity.F_EnCode;
                            }
                            else
                            {
                                billCode     = billCode + departmentEntity.F_FullName;
                                nextBillCode = nextBillCode + departmentEntity.F_FullName;
                            }
                            break;

                        //公司
                        case "4":
                            CompanyEntity companyEntity = companyIBLL.GetEntity(userInfo.companyId);
                            if (codeRuleFormatEntity.formatStr == "code")
                            {
                                billCode     = billCode + companyEntity.F_EnCode;
                                nextBillCode = nextBillCode + companyEntity.F_EnCode;
                            }
                            else
                            {
                                billCode     = billCode + companyEntity.F_FullName;
                                nextBillCode = nextBillCode + companyEntity.F_FullName;
                            }
                            break;

                        //用户
                        case "5":
                            if (codeRuleFormatEntity.formatStr == "code")
                            {
                                billCode     = billCode + userInfo.enCode;
                                nextBillCode = nextBillCode + userInfo.enCode;
                            }
                            else
                            {
                                billCode     = billCode + userInfo.account;
                                nextBillCode = nextBillCode + userInfo.account;
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    coderuleentity.F_CurrentNumber = nextBillCode;
                    SaveEntity(coderuleentity.F_RuleId, coderuleentity, userInfo);
                }
                return(billCode);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
Ejemplo n.º 11
0
        public void TestOutTime()
        {
            LoginUserInfo info = new LoginUserInfo();

            Assert.IsFalse(info.OutTime());
        }
Ejemplo n.º 12
0
        public async Task <LoginUserInfo> GetUserByLoginInfo(string loginId, string passwordStr)
        {
            LoginUserInfo user = await repository.GetUserByLoginInfo(loginId, passwordStr);

            return(user);
        }
Ejemplo n.º 13
0
        public ActionResult ConfigServiceRight(int roleId = -1, int userId = 0)
        {
            //具有国内/国际开发主管角色的登入用户进入该页后,角色下拉列表只列出国内/国际开发主管,
            //否则,列出国内开发主管和国际开发主管两角色:
            SysRoleLogic   roleLogic    = new SysRoleLogic();
            List <SysRole> roleList     = roleLogic.GetRoleList().ToList <SysRole>();
            LoginUserInfo  currentLogin = this.WorkContext.CurrentUser;

            //7表示国内开发主管角色,8表示国际开发主管角色
            if (currentLogin.RoleId == 7 || currentLogin.RoleId == 8)
            {
                roleList = roleList.Where(x => x.RoleId == currentLogin.RoleId).ToList <SysRole>();
            }
            else
            {
                roleList = roleList.Where(x => (x.RoleId == 7 || x.RoleId == 8)).ToList <SysRole>();
            }
            ViewBag.RoleId = new SelectList(roleList, "RoleId", "RoleName");
            if (roleId < 1)
            {
                if (currentLogin.RoleId == 7 || currentLogin.RoleId == 8)
                {
                    ViewBag.CurrentRoleId = currentLogin.RoleId;
                }
                else
                {
                    ViewBag.CurrentRoleId = 7;
                }
            }
            else
            {
                ViewBag.CurrentRoleId = roleId;
            }

            List <SysUser> userList = GetUserList(roleId);

            ViewBag.UserId        = new SelectList(userList, "UserId", "RealName");
            ViewBag.CurrentUserId = userId;

            List <SysRoleRight> roleRightList = new List <SysRoleRight>();

            if (roleId > 0)
            {
                SysApplicationLogic appIdMenuLogic = new SysApplicationLogic();

                //求配置中心权限管理模块的各菜单项:
                List <SysApplicationEntity> appIdMenuList = null;
                SysUserLogic sysUserLogic     = new SysUserLogic();
                SysUser      sysUser          = null;
                int?         selectedUserId   = -1;
                string       selectedUserName = string.Empty;
                switch (roleId)
                {
                case 7:    //国内开发主管角色,目前只求针对国内机票产品线的配置中心权限管理模块的各菜单项:
                    sysUser = sysUserLogic.GetUserInfo(userId);
                    if (sysUser != null)
                    {
                        selectedUserName        = sysUser.RealName;
                        ViewBag.CurrentUserName = selectedUserName;
                    }
                    appIdMenuList = appIdMenuLogic.GetSysApplicationList(-1, -1, "", -1, -1, null, new List <int> {
                        1
                    }, selectedUserName).ToList <SysApplicationEntity>();
                    break;

                case 8:     //国际开发主管角色,目前只求针对国际机票产品线的配置中心权限管理模块的各菜单项:
                    sysUser = sysUserLogic.GetUserInfo(userId);
                    if (sysUser != null)
                    {
                        selectedUserName        = sysUser.RealName;
                        ViewBag.CurrentUserName = selectedUserName;
                    }
                    appIdMenuList = appIdMenuLogic.GetSysApplicationList(-1, -1, "", -1, -1, null, new List <int> {
                        2
                    }, selectedUserName).ToList <SysApplicationEntity>();
                    break;

                default:
                    break;
                }
                ViewBag.AppIdMenuList = appIdMenuList;

                selectedUserId = ViewBag.CurrentUserId as int?;
                roleRightList  = logic.GetRoleRightList(roleId, true, (selectedUserId.HasValue ? Convert.ToInt32(selectedUserId) : -1)).ToList <SysRoleRight>();
            }

            return(View(roleRightList));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Login([FromForm] string userid, [FromForm] string password, [FromForm] bool rememberLogin = false, [FromForm] bool cookie = true)
        {
            var user = await KnifeVirgo.LoadUserFromDB(null, userid, password);

            //如果没有找到则输出错误
            if (user == null)
            {
                return(BadRequest(Localizer["LoginFailed"].Value));
            }
            KnifeVirgo.LoginUserInfo = user;

            if (cookie) // cookie auth
            {
                AuthenticationProperties properties = null;
                if (rememberLogin)
                {
                    properties = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                    };
                }

                var principal = KnifeVirgo.LoginUserInfo.CreatePrincipal();
                // 在上面注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

                List <SimpleMenu> ms     = new List <SimpleMenu>();
                LoginUserInfo     forapi = new LoginUserInfo();
                forapi.Id      = user.Id;
                forapi.ITCode  = user.ITCode;
                forapi.Name    = user.Name;
                forapi.Roles   = user.Roles;
                forapi.Groups  = user.Groups;
                forapi.PhotoId = user.PhotoId;
                var menus = KnifeVirgo.DC.Set <FunctionPrivilege>()
                            .Where(x => x.UserId == user.Id || (x.RoleId != null && user.Roles.Select(x => x.ID).Contains(x.RoleId.Value)))
                            .Select(x => x.MenuItem)
                            .Where(x => x.MethodName == null)
                            .OrderBy(x => x.DisplayOrder)
                            .Select(x => new SimpleMenu
                {
                    Id       = x.ID.ToString().ToLower(),
                    ParentId = x.ParentId.ToString().ToLower(),
                    Text     = x.PageName,
                    Url      = x.Url,
                    Icon     = x.ICon
                }).ToList();
                LocalizeMenu(menus);
                ms.AddRange(menus);

                List <string> urls = new List <string>();
                urls.AddRange(KnifeVirgo.DC.Set <FunctionPrivilege>()
                              .Where(x => x.UserId == user.Id || (x.RoleId != null && user.Roles.Select(x => x.ID).Contains(x.RoleId.Value)))
                              .Select(x => x.MenuItem)
                              .Where(x => x.MethodName != null)
                              .Select(x => x.Url)
                              );
                urls.AddRange(KnifeVirgo.GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
                forapi.Attributes = new Dictionary <string, object>();
                forapi.Attributes.Add("Menus", menus);
                forapi.Attributes.Add("Actions", urls);

                return(Ok(forapi));
            }
            else // jwt auth
            {
                // 在上面注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                              KnifeVirgo.LoginUserInfo.CreatePrincipal(),
                                              new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(15))
                });

                var authService = HttpContext.RequestServices.GetService(typeof(ITokenService)) as ITokenService;

                var token = await authService.IssueTokenAsync(KnifeVirgo.LoginUserInfo);

                return(Content(JsonSerializer.Serialize(token), "application/json"));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// excel 数据导入(未导入数据写入缓存)
        /// </summary>
        /// <param name="templateId">导入模板主键</param>
        /// <param name="fileId">文件ID</param>
        /// <param name="dt">导入数据</param>
        /// <returns></returns>
        public string ImportTable(string templateId, string fileId, DataTable dt)
        {
            int snum = 0;
            int fnum = 0;

            try
            {
                if (dt.Rows.Count > 0)
                {
                    ExcelImportEntity             entity = GetEntity(templateId);
                    List <ExcelImportFieldEntity> list   = (List <ExcelImportFieldEntity>)GetFieldList(templateId);
                    if (entity != null && list.Count > 0)
                    {
                        UserInfo userInfo = LoginUserInfo.Get();
                        // 获取当前表的所有字段
                        IEnumerable <DatabaseTableFieldModel> fieldList = databaseTableIBLL.GetTableFiledList(entity.F_DbId, entity.F_DbTable);
                        Dictionary <string, string>           fieldMap  = new Dictionary <string, string>();
                        foreach (var field in fieldList)// 遍历字段设置每个字段的数据类型
                        {
                            fieldMap.Add(field.f_column, field.f_datatype);
                        }
                        // 拼接导入sql语句
                        string sql      = " INSERT INTO " + entity.F_DbTable + " (";
                        string sqlValue = "(";
                        bool   isfirt   = true;

                        foreach (var field in list)
                        {
                            if (!isfirt)
                            {
                                sql      += ",";
                                sqlValue += ",";
                            }
                            sql      += field.F_Name;
                            sqlValue += "@" + field.F_Name;
                            isfirt    = false;
                        }
                        sql += " ) VALUES " + sqlValue + ")";
                        string sqlonly = " select * from " + entity.F_DbTable + " where ";

                        // 创建一个datatable容器用于保存导入失败的数据
                        DataTable failDt = new DataTable();
                        dt.Columns.Add("导入错误", typeof(string));
                        foreach (DataColumn dc in dt.Columns)
                        {
                            failDt.Columns.Add(dc.ColumnName, dc.DataType);
                        }

                        // 数据字典数据
                        Dictionary <string, List <DataItemDetailEntity> > dataItemMap = new Dictionary <string, List <DataItemDetailEntity> >();
                        // 循环遍历导入
                        foreach (DataRow dr in dt.Rows)
                        {
                            try
                            {
                                var dp = new DynamicParameters(new { });
                                foreach (var col in list)
                                {
                                    string paramName = "@" + col.F_Name;
                                    DbType dbType    = FieldTypeHepler.ToDbType(fieldMap[col.F_Name]);

                                    switch (col.F_RelationType)
                                    {
                                    case 0:    //无关联
                                        dp.Add(col.F_Name, dr[col.F_ColName].ToString(), dbType);
                                        IsOnlyOne(col, sqlonly, dr[col.F_ColName].ToString(), entity.F_DbId, dbType);
                                        break;

                                    case 1:    //GUID
                                        dp.Add(col.F_Name, Guid.NewGuid().ToString(), dbType);
                                        break;

                                    case 2:    //数据字典
                                        string dataItemName = "";
                                        if (!dataItemMap.ContainsKey(col.F_DataItemCode))
                                        {
                                            List <DataItemDetailEntity> dataItemList = dataItemIBLL.GetDetailList(col.F_DataItemCode);
                                            dataItemMap.Add(col.F_DataItemCode, dataItemList);
                                        }
                                        dataItemName = FindDataItemValue(dataItemMap[col.F_DataItemCode], dr[col.F_ColName].ToString(), col.F_ColName);
                                        dp.Add(col.F_Name, dataItemName, dbType);
                                        IsOnlyOne(col, sqlonly, dataItemName, entity.F_DbId, dbType);
                                        break;

                                    case 3:    //数据表
                                        string v = "";
                                        try
                                        {
                                            string[]  dataSources = col.F_DataSourceId.Split(',');
                                            string    strWhere    = " " + dataSources[1] + " =@" + dataSources[1];
                                            string    queryJson   = "{" + dataSources[1] + ":\"" + dr[col.F_ColName].ToString() + "\"}";
                                            DataTable sourceDt    = dataSourceIBLL.GetDataTable(dataSources[0], strWhere, queryJson);
                                            v = sourceDt.Rows[0][0].ToString();
                                            dp.Add(col.F_Name, v, dbType);
                                        }
                                        catch (Exception)
                                        {
                                            throw (new Exception("【" + col.F_ColName + "】 找不到对应的数据"));
                                        }
                                        IsOnlyOne(col, sqlonly, v, entity.F_DbId, dbType);
                                        break;

                                    case 4:    //固定值
                                        dp.Add(col.F_Name, col.F_Value, dbType);
                                        break;

                                    case 5:    //操作人ID
                                        dp.Add(col.F_Name, userInfo.userId, dbType);
                                        break;

                                    case 6:    //操作人名字
                                        dp.Add(col.F_Name, userInfo.realName, dbType);
                                        break;

                                    case 7:    //操作时间
                                        dp.Add(col.F_Name, DateTime.Now, dbType);
                                        break;
                                    }
                                }
                                databaseLinkIBLL.ExecuteBySql(entity.F_DbId, sql, dp);
                                snum++;
                            }
                            catch (Exception ex)
                            {
                                fnum++;
                                if (entity.F_ErrorType == 0)// 如果错误机制是终止
                                {
                                    dr["导入错误"] = ex.Message + "【之后数据未被导入】";
                                    failDt.Rows.Add(dr.ItemArray);
                                    break;
                                }
                                else
                                {
                                    dr["导入错误"] = ex.Message;
                                    failDt.Rows.Add(dr.ItemArray);
                                }
                            }
                        }

                        // 写入缓存如果有未导入的数据
                        if (failDt.Rows.Count > 0)
                        {
                            string errordt = failDt.ToJson();

                            cache.Write <string>(cacheKey + fileId, errordt, CacheId.excel);
                        }
                    }
                }


                return(snum + "|" + fnum);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 删除单个台账管理信息
        /// </summary>
        /// <param name="Parameter"></param>
        /// <returns></returns>
        public ReturnMsg DeleteEqui(InvokeEntity Parameter)
        {
            userInfo = BasePubCommon.FindLoginUserInfo(Parameter.token);
            var JO   = JsonConvert.DeserializeObject <JObject>(Parameter.obj.ToString());
            var code = JO["equiCode"].ToString();

            this.sqlConn = Parameter.SqlConnection;
            var  conn = new BaseSQL(sqlConn);
            bool flag = false;

            try
            {
                Fail("删除失败");
                //删除设备以及关联的表信息
                conn.BeginTrans();


                //删除设备信息
                string         Sql   = "delete from sfcdatequipmentinfo where code=@code";
                CmdParameter[] paras = new CmdParameter[1];
                paras[0] = new CmdParameter()
                {
                    DBtype = DBType.String, ParameterName = "@code", Value = code
                };
                flag = conn.ExeSql(Sql, paras);

                //删除附件信息
                Sql  = "delete from sfcdatattachment  where equipmentinfocode=@code";
                flag = conn.ExeSql(Sql, paras);

                //删除文档信息
                Sql  = "delete from sfcdatdocument  where equipmentinfocode=@code";
                flag = conn.ExeSql(Sql, paras);

                //删除图片信息
                Sql  = "delete from sfcdatpic  where equipmentinfocode=@code";
                flag = conn.ExeSql(Sql, paras);

                //删除维修记录
                Sql  = "delete from sfcdatmaintenancerecord  where equipmentcode=@code";
                flag = conn.ExeSql(Sql, paras);

                //删除调拨记录
                Sql  = "delete from sfcdattransferrecord  where equipmentinfocode=@code";
                flag = conn.ExeSql(Sql, paras);

                //删除报废记录
                Sql  = "delete from sfcdatscraprecord  where equipmentinfocode =@code";
                flag = conn.ExeSql(Sql, paras);

                //删除其它异动
                Sql  = "delete from sfcdatothermove  where equipmentinfocode =@code";
                flag = conn.ExeSql(Sql, paras);

                //删除定期检修
                Sql  = "delete from sfcdatrepairinfo  where equipmentcode =@code";
                flag = conn.ExeSql(Sql, paras);

                conn.Commit();
                Success();
                return(resultData);
            }
            catch (Exception ex)
            {
                conn.Rollback();
                return(resultData);
            }
        }
Ejemplo n.º 17
0
 private void LogUserInfo(string actionUrl, string actionName, string requestType, bool issuccess, string desc, LoginUserInfo user)
 {
     using (BaseDbContext db = new BaseDbContext())
     {
         db.SysLogs.Add(new SysLog
         {
             CN_ACTIONURL   = actionUrl,
             CN_USERIP      = actionName,
             CN_DESC        = desc,
             CN_REQUESTTYPE = requestType,
             CN_ISSUCCESS   = issuccess,
             CN_USERID      = user.UserId,
             CN_USERNAME    = user.Name,
             CN_USERLOGIN   = user.Login,
             CN_DT_DATE     = DateTime.Now
         });
         db.SaveChanges();
     }
 }
Ejemplo n.º 18
0
        public string getOrgID()
        {
            LoginUserInfo vUserInf = getLoginUserInfo();

            return(vUserInf.ORG_ID);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// 编辑调用
 /// </summary>
 /// <param name="keyValue"></param>
 public void Modify(string keyValue)
 {
     this.ID           = keyValue;
     this.S_UpdateBy   = LoginUserInfo.Get().userId;
     this.S_UpdateDate = DateTime.Now;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// User login.
        /// </summary>
        /// <param name="dto">Login information.</param>
        /// <returns></returns>
        public Task <string> Login(LoginDTO login)
        {
            return(Task.Run(() =>
            {
                if (login == null)
                {
                    return ResponseFail.Json("", "用户名和密码为空");
                }
                else if (!string.IsNullOrEmpty(login.AuthToken))
                {
                    LoginUserInfo userInfo = UserLoginCache.FindUser(login.AuthToken);
                    if (userInfo.ID == 0)
                    {
                        return ResponseFail.Json("[AuthToken]无效");
                    }

                    if (!userInfo.OutTime())
                    {
                        return ResponseSuccess.Json(UserLoginCache.FindUser(login.AuthToken));
                    }
                }
                else if (string.IsNullOrEmpty(login.UserName))
                {
                    return ResponseFail.Json("", "用户名为空");
                }
                else if (string.IsNullOrEmpty(login.Password))
                {
                    return ResponseFail.Json("", "密码为空");
                }
                else if (string.IsNullOrEmpty(login.TimeStamp))
                {
                    return ResponseFail.Json("", "参数异常,请检查[TimeStamp]");
                }
                else if (!Utils.CompareMD5(login.Token, string.Format("{0}-{1}", login.UserName, login.TimeStamp)))
                {
                    return ResponseFail.Json("", "参数异常,请检查[Token]");
                }

                User user = context.Users.ToList().Find(t => t.UserName == login.UserName);
                if (user == null)
                {
                    return CheckLoginInfo();
                }
                else if (string.IsNullOrEmpty(user.Password))
                {
                    return ResponseFail.Json("", "未设置密码");
                }
                else
                {
                    if (user.Password == login.Password)
                    {
                        string token = Utils.MD5(string.Format("{0}-{1}-{2}", user.UserName, login.TimeStamp, DateTime.Now.ToUniversalTime().ToString()));
                        UserLoginCache.AddUserCache(token, user);
                        return ResponseSuccess.Json(UserLoginCache.FindUser(token));
                    }
                    else
                    {
                        return CheckLoginInfo();
                    }
                }
            }));
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     加载用户信息
        /// </summary>
        /// <param name="loginUserInfo"></param>
        public bool SyncUserData(LoginUserInfo loginUserInfo)
        {
            AccessToken = loginUserInfo.ACCESSTOKEN;
            UserID      = loginUserInfo.ID;
            var userInfo = (new BfUserManager()).GetItemByCode(loginUserInfo.CODE);

            if (userInfo != null && userInfo.ID > 0)
            {
                UserID   = userInfo.ID;
                UserCode = userInfo.CODE;
                UserName = userInfo.NAME;
                var modules    = (new BfModuleManager()).SelectObjectByUserID(UserID);
                var moduleList = new List <ModuleInfo>();
                if (modules != null)
                {
                    foreach (var module in modules)
                    {
                        var mo = new ModuleInfo
                        {
                            SystemID    = module.ID,
                            MODULE_CODE = module.CODE,
                            MODULE_NAME = module.NAME
                        };
                        moduleList.Add(mo);
                    }
                }
                ModuleInfos = moduleList;

                #region

                Roles = (new BfRoleUserManager()).GetRoleByUser(UserID);

                #endregion

                #region 操作权限

                var operationInfos       = (new BfModuleOperationManager()).SelectOperationByUserID(UserID);
                var moduleOperationInfos = new List <ModuleOperationInfo>();
                if (operationInfos != null)
                {
                    foreach (var ro in operationInfos)
                    {
                        var role = new ModuleOperationInfo
                        {
                            MODULE_CODE    = ro.MODULE_CODE,
                            OPERATION_CODE = ro.CODE
                        };
                        moduleOperationInfos.Add(role);
                    }
                }
                RoleOperation = moduleOperationInfos;
                MemuTree.Instance.GetModuleInfo(true);

                #endregion

                if (HttpContext.Current.Session["LoginTime"] == null)
                {
                    HttpContext.Current.Session["LoginTime"] = DateTime.Now;
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> Login([FromForm] string account, [FromForm] string password, [FromForm] bool rememberLogin = false)
        {
            var rv = await DC.Set <FrameworkUser>().Where(x => x.ITCode.ToLower() == account.ToLower() && x.Password == Utils.GetMD5String(password)).Select(x => new { itcode = x.ITCode, id = x.ID }).SingleOrDefaultAsync();

            if (rv == null)
            {
                ModelState.AddModelError(" ", Localizer["Sys.LoginFailed"]);
                return(BadRequest(ModelState.GetErrorJson()));
            }
            LoginUserInfo user = new LoginUserInfo
            {
                ITCode = rv.itcode,
                UserId = rv.id.ToString()
            };

            await user.LoadBasicInfoAsync(Wtm);

            Wtm.LoginUserInfo = user;

            AuthenticationProperties properties = null;

            if (rememberLogin)
            {
                properties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                };
            }

            var principal = Wtm.LoginUserInfo.CreatePrincipal();
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

            List <SimpleMenu> ms     = new List <SimpleMenu>();
            LoginUserInfo     forapi = new LoginUserInfo();

            forapi.ITCode  = user.ITCode;
            forapi.Name    = user.Name;
            forapi.Roles   = user.Roles;
            forapi.Groups  = user.Groups;
            forapi.PhotoId = user.PhotoId;
            var menus = DC.Set <FunctionPrivilege>()
                        .Where(x => x.RoleCode != null && user.Roles.Select(x => x.RoleCode).Contains(x.RoleCode))
                        .Select(x => x.MenuItem)
                        .Where(x => x.MethodName == null)
                        .OrderBy(x => x.DisplayOrder)
                        .Select(x => new SimpleMenu
            {
                Id       = x.ID.ToString().ToLower(),
                ParentId = x.ParentId.ToString().ToLower(),
                Text     = x.PageName,
                Url      = x.Url,
                Icon     = x.Icon
            }).ToList();

            LocalizeMenu(menus);
            ms.AddRange(menus);

            List <string> urls = new List <string>();

            urls.AddRange(DC.Set <FunctionPrivilege>()
                          .Where(x => x.RoleCode != null && user.Roles.Select(x => x.RoleCode).Contains(x.RoleCode))
                          .Select(x => x.MenuItem)
                          .Where(x => x.MethodName != null)
                          .Select(x => x.Url)
                          );
            urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
            forapi.Attributes = new Dictionary <string, object>();
            forapi.Attributes.Add("Menus", menus);
            forapi.Attributes.Add("Actions", urls);

            return(Ok(forapi));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 获取正式发布的文件
        /// </summary>
        /// <param name="keyword">查询关键字</param>
        /// <param name="folderId">文件夹id</param>
        /// <returns></returns>
        public IEnumerable <FileBInfoEntity> GetPublishList(string keyword, string folderId)
        {
            UserInfo userInfo = LoginUserInfo.Get();
            List <FileAuthEntity>  authList = new List <FileAuthEntity>();
            List <FileBInfoEntity> list     = new List <FileBInfoEntity>();

            if (!userInfo.isSystem)
            {
                string roleIds = userInfo.roleIds;
                if (string.IsNullOrEmpty(roleIds))
                {
                    return(new List <FileBInfoEntity>());
                }
                else
                {
                    roleIds  = "('" + roleIds.Replace(",", "','") + "')";
                    authList = (List <FileAuthEntity>) this.BaseRepository().FindList <FileAuthEntity>(" select * from lr_base_fileauth where F_ObjId in " + roleIds + " AND  F_Time >= @ftime ORDER BY F_Type,F_Level ", new { ftime = DateTime.Now });
                }
            }



            if (string.IsNullOrEmpty(keyword))
            {
                list.AddRange(GetFolderList2(keyword, folderId, authList, userInfo));
            }

            var strSql = new StringBuilder();

            strSql.Append(" select t.*,t1.F_Ver,t1.F_FileId,t1.F_PFiled,t3.F_FileSize,t3.F_FileType,1 as Type,'1,2,3,4,5,6' as F_AuthType from lr_base_fileinfo t ");
            strSql.Append(" LEFT JOIN lr_base_filelist t1 on t1.F_FileInfoId = t.F_Id ");
            //strSql.Append(" LEFT JOIN lr_base_fileauth t2 on t2.F_FileInfoId = t.F_Id ");
            strSql.Append(" LEFT JOIN LR_Base_AnnexesFile t3 on t3.F_FolderId = t1.F_FileId ");
            strSql.Append(" where t.F_DeleteMark = 0 AND t.F_IsPublish = 1 AND t1.F_IsPublish = 1 ");



            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = "%" + keyword + "%";
                strSql.Append(" AND (t.F_Name like @keyword OR t.F_KeyWord like @keyword ) ");
            }
            else
            {
                strSql.Append(" AND t.F_Folder = @folderId ");
            }
            var fileList = this.BaseRepository().FindList <FileBInfoEntity>(strSql.ToString(), new { keyword, folderId });



            if (!userInfo.isSystem)
            {
                foreach (var item in fileList)
                {
                    var  roleIdList = userInfo.roleIds.Split(',');
                    bool flag       = false;
                    item.F_AuthType = "";
                    foreach (var roleIdItem in roleIdList)
                    {
                        var authList2 = authList.FindAll(t => t.F_FileInfoId == item.F_Id && t.F_ObjId == roleIdItem);
                        if (authList2.Count > 0)
                        {
                            flag = true;
                            if (item.F_AuthType != "")
                            {
                                item.F_AuthType += ",";
                            }
                            item.F_AuthType += authList2[0].F_AuthType;
                        }
                    }

                    if (flag)
                    {
                        list.Add(item);
                    }
                }
            }
            else
            {
                list.AddRange(fileList);
            }
            return(list);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 设置查询语句
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <returns></returns>
        public bool SetWhereSql(string url)
        {
            try
            {
                UserInfo userInfo = LoginUserInfo.Get();
                if (userInfo.isSystem)
                {
                    return(true);
                }
                // 判断该接口注册了
                InterfaceEntity interfaceEntity = interfaceIBLL.GetEntityByUrl(url);
                if (interfaceEntity == null)
                {
                    // 如果接口没有注册则不作过滤
                    return(true);
                }
                else
                {
                    List <DataAuthorizeRelationEntity> relationList = (List <DataAuthorizeRelationEntity>)GetRelationList(interfaceEntity.F_Id);
                    if (relationList.Count > 0)
                    {
                        relationList = relationList.FindAll(t => t.F_ObjectId.Equals(userInfo.userId) || t.F_ObjectId.Like(userInfo.roleIds));
                        if (relationList.Count > 0)
                        {
                            string  whereSql = "";
                            DbWhere dbWhere  = new DbWhere();
                            dbWhere.dbParameters = new List <FieldValueParam>();

                            int relationnum = 0;
                            foreach (var item in relationList)
                            {
                                if (whereSql != "")
                                {
                                    whereSql += " OR ";
                                }
                                whereSql += " ( ";
                                string strSql = "";
                                List <DataAuthorizeConditionEntity> conditionList = (List <DataAuthorizeConditionEntity>)GetDataAuthorizeConditionList(item.F_Id);

                                if (!string.IsNullOrEmpty(item.F_Formula))
                                {
                                    strSql = item.F_Formula;
                                    for (int i = 1; i < conditionList.Count + 1; i++)
                                    {
                                        strSql = strSql.Replace("" + i, "{@learun" + i + "learun@}");
                                    }
                                }
                                else
                                {
                                    for (int i = 1; i < conditionList.Count + 1; i++)
                                    {
                                        if (strSql != "")
                                        {
                                            strSql += " AND ";
                                        }
                                        strSql += " {@learun" + i + "learun@} ";
                                    }
                                }

                                int num = 1;

                                foreach (var conditionItem in conditionList)
                                {
                                    string strone = " " + conditionItem.F_FieldId;
                                    string value  = " @" + conditionItem.F_FieldId + relationnum;

                                    FieldValueParam dbParameter = new FieldValueParam();
                                    dbParameter.name  = conditionItem.F_FieldId + relationnum;
                                    dbParameter.value = getValue(conditionItem.F_FiledValueType, conditionItem.F_FiledValue);
                                    dbParameter.type  = conditionItem.F_FieldType;
                                    dbWhere.dbParameters.Add(dbParameter);
                                    //[{ value: 1, text: '等于' }, { value: 2, text: '大于' }, { value: 3, text: '大于等于' }, { value: 4, text: '小于' }, { value: 5, text: '小于等于' }, { value: 6, text: '包含' }, { value: 7, text: '包含于' }, { value: 8, text: '不等于' }, { value: 9, text: '不包含' }, { value: 10, text: '不包含于' }],
                                    switch (conditionItem.F_Symbol)
                                    {
                                    case 1:    // 等于
                                        strone += " = " + value;
                                        break;

                                    case 2:    // 大于
                                        strone += " > " + value;
                                        break;

                                    case 3:    // 大于等于
                                        strone += " >= " + value;
                                        break;

                                    case 4:    // 小于
                                        strone += " < " + value;
                                        break;

                                    case 5:    // 小于等于
                                        strone += " <= " + value;
                                        break;

                                    case 6:    // 包含
                                        strone += " like %" + value + "%";
                                        break;

                                    case 7:    // 包含于
                                        strone += " in ( '" + value.Replace(",", "','") + "' )";
                                        break;

                                    case 8:    // 不等于
                                        strone += " != " + value;
                                        break;

                                    case 9:    // 不包含
                                        strone += " not like %" + value + "%";
                                        break;

                                    case 10:    // 不包含于
                                        strone += " not in ( '" + value.Replace(",", "','") + "' )";
                                        break;

                                    default:
                                        break;
                                    }
                                    strone += " ";
                                    strSql  = strSql.Replace("{@learun" + num + "learun@}", strone);
                                    num++;
                                }

                                whereSql += strSql;
                                whereSql += " ) ";
                                relationnum++;
                            }
                            dbWhere.sql = whereSql;
                            WebHelper.AddHttpItems("DataAhthorCondition", dbWhere);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        // 该接口没做权限过滤
                        return(true);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 获取正式发布的文件
        /// </summary>
        /// <param name="keyword">查询关键字</param>
        /// <returns></returns>
        public IEnumerable <FileBInfoEntity> GetDeleteList(string keyword)
        {
            List <FileBInfoEntity> list = new List <FileBInfoEntity>();

            var strSql = new StringBuilder();

            strSql.Append(" select t.*,t1.F_Ver,t1.F_FileId,t1.F_PFiled,t3.F_FileSize,t3.F_FileType,1 as Type,'1,2,3,4,5,6' as F_AuthType from lr_base_fileinfo t ");
            strSql.Append(" LEFT JOIN lr_base_filelist t1 on t1.F_FileInfoId = t.F_Id ");
            strSql.Append(" LEFT JOIN LR_Base_AnnexesFile t3 on t3.F_FolderId = t1.F_FileId ");
            strSql.Append(" where t.F_DeleteMark = 1 AND t.F_IsPublish = 1 AND t1.F_IsPublish = 1 ");

            list.AddRange(this.BaseRepository().FindList <FileBInfoEntity>(strSql.ToString(), new { keyword }));

            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = "%" + keyword + "%";
                strSql.Append(" AND t.F_Name like @keyword ");
            }


            UserInfo userInfo = LoginUserInfo.Get();

            if (!userInfo.isSystem)
            {
                string postIds = userInfo.postIds;
                if (string.IsNullOrEmpty(postIds))
                {
                    return(list);
                }
                else
                {
                    postIds = "('" + postIds.Replace(",", "','") + "')";

                    var authList = (List <FileAuthEntity>) this.BaseRepository().FindList <FileAuthEntity>(" select * from lr_base_fileauth where F_ObjId in " + postIds + " AND  F_Time <= ftime ", new { ftime = DateTime.Now });


                    List <FileBInfoEntity> list2 = new List <FileBInfoEntity>();

                    foreach (var item in list)
                    {
                        var fileList = authList.FindAll(t => t.F_FileInfoId == item.F_Id);
                        if (fileList.Count > 0)
                        {
                            string authType = "";
                            foreach (var fileItem in fileList)
                            {
                                if (authType != "")
                                {
                                    authType += ",";
                                }
                                authType += fileItem.F_AuthType;
                            }
                            item.F_AuthType = authType;
                            list2.Add(item);
                        }
                    }

                    return(list2);
                    //strSql.Append(" AND t2.F_ObjId in " + postIds);
                }
            }



            return(list);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="type">数据类型</param>
        /// <param name="value">数据值</param>
        /// <returns></returns>
        private string getValue(int?type, string value)
        {
            UserInfo userInfo = LoginUserInfo.Get();
            //1.文本2.登录者ID3.登录者账号4.登录者公司5.登录者部门6.登录者岗位7.登录者角色
            string text = "";

            switch (type)
            {
            case 1:    // 文本
                text = value;
                break;

            case 2:    // 登录者ID
                text = userInfo.userId;
                break;

            case 3:    // 登录者账号
                text = userInfo.account;
                break;

            case 4:    // 登录者公司
                text = userInfo.companyId;
                break;

            case 41:    // 登录者公司及下属公司
                foreach (var id in userInfo.companyIds)
                {
                    if (text != "")
                    {
                        text += ",";
                    }
                    text += id;
                }
                break;

            case 5:    // 登录者部门
                text = userInfo.departmentId;
                break;

            case 51:    // 登录者部门及下属部门
                foreach (var id in userInfo.departmentIds)
                {
                    if (text != "")
                    {
                        text += ",";
                    }
                    text += id;
                }
                break;

            case 6:    // 登录者岗位
                text = userInfo.postIds;
                break;

            case 7:    // 登录者角色
                text = userInfo.roleIds;
                break;

            default:
                text = value;
                break;
            }
            return(text);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// IP地址过滤
        /// </summary>
        /// <returns></returns>
        public bool FilterIP()
        {
            string[] roleIdList = null;
            UserInfo userInfo   = LoginUserInfo.Get();

            if (userInfo.isSystem)
            {
                return(true);
            }

            if (!string.IsNullOrEmpty(userInfo.roleIds))
            {
                roleIdList = userInfo.roleIds.Split(',');
            }

            #region 黑名单处理
            IEnumerable <FilterIPEntity> blackIPList = GetList(userInfo.userId, "0");
            bool isBlack = CheckArea(blackIPList);
            if (isBlack)
            {
                return(false);
            }
            if (roleIdList != null)
            {
                foreach (string role in roleIdList)
                {
                    blackIPList = GetList(role, "0");
                    isBlack     = CheckArea(blackIPList);
                    if (isBlack)
                    {
                        return(false);
                    }
                }
            }
            #endregion

            #region 白名单处理
            bool makeWhite = false;
            List <FilterIPEntity> whiteIPList = (List <FilterIPEntity>)GetList(userInfo.userId, "1");
            if (whiteIPList.Count > 0)
            {
                makeWhite = true;
            }
            bool isWhite = CheckArea(whiteIPList);
            if (isWhite)
            {
                return(true);
            }
            if (roleIdList != null)
            {
                foreach (string role in roleIdList)
                {
                    whiteIPList = (List <FilterIPEntity>)GetList(role, "1");
                    if (whiteIPList.Count > 0)
                    {
                        makeWhite = true;
                    }
                    isWhite = CheckArea(whiteIPList);
                    if (isWhite)
                    {
                        return(true);
                    }
                }
            }
            if (makeWhite)
            {
                return(false);
            }
            #endregion
            return(true);
        }
Ejemplo n.º 28
0
        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            List <Guid> oldIDs = null;

            if (DpType == DpTypeEnum.User)
            {
                oldIDs = DC.Set <DataPrivilege>().Where(x => x.UserId == Entity.UserId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList();
            }
            else
            {
                oldIDs = DC.Set <DataPrivilege>().Where(x => x.GroupId == Entity.GroupId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList();
            }
            foreach (var oldid in oldIDs)
            {
                DataPrivilege dp = new DataPrivilege {
                    ID = oldid
                };
                DC.Set <DataPrivilege>().Attach(dp);
                DC.DeleteEntity(dp);
            }
            if (IsAll == true)
            {
                if (DpType == DpTypeEnum.User)
                {
                    DataPrivilege dp = new DataPrivilege();
                    dp.RelateId  = null;
                    dp.UserId    = Entity.UserId;
                    dp.TableName = this.Entity.TableName;
                    dp.DomainId  = this.Entity.DomainId;
                    DC.Set <DataPrivilege>().Add(dp);
                }
                else
                {
                    DataPrivilege dp = new DataPrivilege();
                    dp.RelateId  = null;
                    dp.GroupId   = Entity.GroupId;
                    dp.TableName = this.Entity.TableName;
                    dp.DomainId  = this.Entity.DomainId;
                    DC.Set <DataPrivilege>().Add(dp);
                }
            }
            else
            {
                if (SelectedItemsID != null)
                {
                    if (DpType == DpTypeEnum.User)
                    {
                        foreach (var id in SelectedItemsID)
                        {
                            DataPrivilege dp = new DataPrivilege();
                            dp.RelateId  = id;
                            dp.UserId    = Entity.UserId;
                            dp.TableName = this.Entity.TableName;
                            dp.DomainId  = this.Entity.DomainId;
                            DC.Set <DataPrivilege>().Add(dp);
                        }
                    }
                    else
                    {
                        foreach (var id in SelectedItemsID)
                        {
                            DataPrivilege dp = new DataPrivilege();
                            dp.RelateId  = id;
                            dp.GroupId   = Entity.GroupId;
                            dp.TableName = this.Entity.TableName;
                            dp.DomainId  = this.Entity.DomainId;
                            DC.Set <DataPrivilege>().Add(dp);
                        }
                    }
                }
            }
            await DC.SaveChangesAsync();

            if (DpType == DpTypeEnum.User)
            {
                await LoginUserInfo.RemoveUserCache(Entity.UserId.ToString());
            }
            else
            {
                var userids = DC.Set <FrameworkUserGroup>().Where(x => x.GroupId == Entity.GroupId).Select(x => x.UserId.ToString()).ToArray();
                await LoginUserInfo.RemoveUserCache(userids);
            }
        }
Ejemplo n.º 29
0
        public IActionResult CheckUserInfo()
        {
            if (LoginUserInfo == null)
            {
                return(BadRequest());
            }
            else
            {
                var forapi = new LoginUserInfo();
                forapi.Id      = LoginUserInfo.Id;
                forapi.ITCode  = LoginUserInfo.ITCode;
                forapi.Name    = LoginUserInfo.Name;
                forapi.Roles   = LoginUserInfo.Roles;
                forapi.Groups  = LoginUserInfo.Groups;
                forapi.PhotoId = LoginUserInfo.PhotoId;

                var ms      = new List <SimpleMenu>();
                var roleIDs = LoginUserInfo.Roles.Select(x => x.ID).ToList();

                var menus = DC.Set <FunctionPrivilege>()
                            .AsNoTracking()
                            .Where(x => x.UserId == LoginUserInfo.Id || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                            .Select(x => x.MenuItem).Distinct()
                            .Where(x => x.MethodName == null)
                            .OrderBy(x => x.DisplayOrder)
                            .Select(x => new SimpleMenu
                {
                    Id       = x.ID.ToString().ToLower(),
                    ParentId = x.ParentId.ToString().ToLower(),
                    Text     = x.PageName,
                    Url      = x.Url,
                    Icon     = x.ICon
                }).ToList();
                var folders = DC.Set <FrameworkMenu>().AsNoTracking().Where(x => x.FolderOnly == true).OrderBy(x => x.DisplayOrder).Select(x => new SimpleMenu
                {
                    Id       = x.ID.ToString().ToLower(),
                    ParentId = x.ParentId.ToString().ToLower(),
                    Text     = x.PageName,
                    Url      = x.Url,
                    Icon     = x.ICon
                }).ToList();
                ms.AddRange(folders);
                foreach (var item in menus)
                {
                    if (folders.Any(x => x.Id == item.Id) == false)
                    {
                        ms.Add(item);
                    }
                }
                List <string> urls = new List <string>();
                urls.AddRange(DC.Set <FunctionPrivilege>()
                              .AsNoTracking()
                              .Where(x => x.UserId == LoginUserInfo.Id || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
                              .Select(x => x.MenuItem).Distinct()
                              .Where(x => x.MethodName != null)
                              .Select(x => x.Url).ToList()
                              );
                urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
                forapi.Attributes = new Dictionary <string, object>();
                forapi.Attributes.Add("Menus", ms);
                forapi.Attributes.Add("Actions", urls);
                return(Ok(forapi));
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 获取树形数据
        /// </summary>
        /// <returns></returns>
        public List <TreeModel> GetTree()
        {
            var list = (List <FolderEntity>)GetList("", "");

            list.Add(new FolderEntity()
            {
                F_Id   = "0",
                F_PId  = "00000",
                F_Name = "主目录"
            });

            UserInfo userInfo = LoginUserInfo.Get();

            if (!userInfo.isSystem)
            {
                string roleIds = userInfo.roleIds;
                if (string.IsNullOrEmpty(roleIds))
                {
                    return(new List <TreeModel>());
                }
                else
                {
                    roleIds = "('" + roleIds.Replace(",", "','") + "')";
                    var authList = (List <FileAuthEntity>)folderService.BaseRepository().FindList <FileAuthEntity>(" select * from lr_base_fileauth where F_ObjId in " + roleIds + " AND  F_Time >= @ftime ORDER BY F_Type,F_Level ", new { ftime = DateTime.Now });
                    List <FolderEntity> list2 = new List <FolderEntity>();
                    foreach (var item in list)
                    {
                        item.F_AuthType = "1";
                        var roleIdList = userInfo.roleIds.Split(',');
                        foreach (var roleIdItem in roleIdList)
                        {
                            var authList2 = authList.FindAll(t => t.F_FileInfoId == item.F_Id && t.F_ObjId == roleIdItem);
                            if (authList2.Count > 0)
                            {
                                if (authList2[0].F_Type != 2 && authList2[0].F_AuthType.IndexOf("2") != -1)
                                {
                                    item.F_AuthType = "2";
                                    break;
                                }
                            }
                        }
                    }
                }
            }



            List <TreeModel> treeList = new List <TreeModel>();

            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id         = item.F_Id;
                node.text       = item.F_Name;
                node.value      = item.F_Id;
                node.showcheck  = false;
                node.checkstate = 0;
                node.isexpand   = true;
                node.parentId   = item.F_PId;
                node.checkstate = 2; //1表示没有权限,2表示有权限

                if (!userInfo.isSystem)
                {
                    if (item.F_AuthType == "2")
                    {
                        node.checkstate = 2;
                    }
                    else
                    {
                        node.checkstate = 1;
                        node.text      += "【无权限】";
                    }
                }

                treeList.Add(node);
            }
            return(treeList.ToTree());
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 处理当前的流程Approve/Refuse。
        /// </summary>
        /// <param name="userInfo">用户、部门、公司对象</param>
        /// <param name="applyId">申请单ID</param>
        /// <param name="msgsendto">发送消息给谁</param>
        /// <param name="opinion">处理意见</param>
        /// <param name="is_proc">当前流程是否通过,1为通过,2为拒绝</param>
        /// <param name="selprocuser">流程处理人</param>
        private void ProcessApplyFlow(LoginUserInfo userInfo, string applyId, string msgsendto, string opinion, int is_proc, string selprocuser)
        {
            ApplyInfo applyInfo = BLLFactory <Apply> .Instance.FindByID(applyId);

            ApplyFlowInfo flowInfo = BLLFactory <ApplyFlow> .Instance.GetFirstUnHandledFlow(applyId);

            if (applyInfo != null && flowInfo != null)
            {
                #region 计算处理用时

                string last_time = applyInfo.ProcTime;
                if (string.IsNullOrEmpty(last_time))
                {
                    last_time = applyInfo.Edittime.ToString("yyyy-MM-dd HH:mm:ss");
                }
                long deltatime = (long)DateTime.Now.Subtract(Convert.ToDateTime(last_time)).TotalSeconds;

                #endregion

                int is_auth = BLLFactory <ApplyUser> .Instance.GetCountByApplyIdAndUserId(applyId, userInfo.ID.ToInt32()) > 0 ? 0 : 1;

                if (applyInfo.ProcType == (int)ProcType.会签)
                {
                    #region 会签处理
                    //更新会签记录
                    BLLFactory <ApplySign> .Instance.UpdateSignInfo(applyId, flowInfo.ID, userInfo.ID.ToInt32(), opinion, is_proc);

                    //判断是否完成会签
                    var signFinished = BLLFactory <ApplySign> .Instance.IsSignFinished(flowInfo.ID);

                    if (signFinished)
                    {
                        //判断是否全部通过会签
                        var signPassed = BLLFactory <ApplySign> .Instance.IsSignPassed(flowInfo.ID);

                        //如果全部会签流程处理完毕
                        var signMessage = signPassed ? "会签通过" : "会签不通过";
                        flowInfo.ProcTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        //在发起人未审批前,会签不完成
                        //flowInfo.IsProc = signPassed ? (int)ApplyStatus.已完成 : (int)ApplyStatus.已退回;
                        flowInfo.MsgSendTo = msgsendto;
                        flowInfo.Deltatime = Convert.ToInt32(deltatime);
                        flowInfo.Opinion   = signMessage;
                        BLLFactory <ApplyFlow> .Instance.Update(flowInfo, flowInfo.ID);

                        //更新流程状态(审批状态,未处理,让发起人审批是否提交)
                        applyInfo.Status   = ApplyStatus.处理中;
                        applyInfo.ProcType = (int)ProcType.审批;
                        BLLFactory <Apply> .Instance.Update(applyInfo, applyId);

                        var applyUserInfo = new ApplyUserInfo(applyId, applyInfo.ProcUser.ToInt32());
                        BLLFactory <ApplyUser> .Instance.Insert(applyUserInfo);

                        //保存申请单日志(系统流程日志)
                        var content = string.Format("该申请在流程环节[{0}][{1}]。", flowInfo.FlowName, signMessage);
                        BLLFactory <ApplyLog> .Instance.AddApplyLog(applyId, userInfo.ID.ToInt32(), content);
                    }
                    #endregion
                }
                //else if(applyInfo.ProcType == (int)ProcType.阅办)
                //{
                //    //阅办处理
                //}
                else
                {
                    #region 更新流程及处理单信息
                    flowInfo.ProcUid   = userInfo.ID.ToInt32();
                    flowInfo.ProcTime  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    flowInfo.IsProc    = is_proc;
                    flowInfo.MsgSendTo = msgsendto;
                    flowInfo.Deltatime = Convert.ToInt32(deltatime);
                    flowInfo.Opinion   = opinion;
                    BLLFactory <ApplyFlow> .Instance.Update(flowInfo, flowInfo.ID);

                    #endregion

                    if (is_proc == (int)ApplyIsProc.拒绝)
                    {
                        #region 拒绝流程

                        //更新流程状态
                        applyInfo.Status   = ApplyStatus.已退回;
                        applyInfo.ProcType = 0;
                        applyInfo.ProcUser = "";
                        BLLFactory <Apply> .Instance.Update(applyInfo, applyId);

                        //拒绝流程后,删除申请单的所有流程用户
                        BLLFactory <ApplyUser> .Instance.DeleteByApplyId(applyId);

                        //保存申请单日志(系统流程日志)
                        string   content  = string.Format("申请单({0})已经被退回", applyInfo.Title);
                        FormInfo formInfo = BLLFactory <Form> .Instance.FindByID(applyInfo.FormId);

                        if (formInfo != null)
                        {
                            content = string.Format("用户ID为 {0},于 {1} 创建的 {2}({3}) 已经被退回。",
                                                    applyInfo.Editor, applyInfo.Edittime, formInfo.FormName, applyInfo.Title);
                        }

                        BLLFactory <ApplyLog> .Instance.AddApplyLog(applyId, userInfo.ID.ToInt32(), content);

                        //"您已经退回了该申请。";
                        #endregion
                    }
                    else
                    {
                        #region 批准流程后续处理
                        //该申请单的下一处理流程
                        ApplyFlowInfo nextFlowInfo = BLLFactory <ApplyFlow> .Instance.GetNextUnHandledFlow(applyId, flowInfo.ID);

                        if (nextFlowInfo != null)
                        {
                            selprocuser = selprocuser.Trim();
                            if (!string.IsNullOrEmpty(selprocuser) && selprocuser != nextFlowInfo.ProcUser)
                            {
                                nextFlowInfo.ProcUser = selprocuser;
                                BLLFactory <ApplyFlow> .Instance.Update(nextFlowInfo, nextFlowInfo.ID);
                            }
                        }

                        //保存申请单日志(系统流程日志)
                        var content = string.Format("在流程环节[{0}]用户批准了申请。", flowInfo.FlowName);
                        BLLFactory <ApplyLog> .Instance.AddApplyLog(applyId, userInfo.ID.ToInt32(), content);

                        #endregion
                    }

                    //更新处理单最后处理时间
                    applyInfo.ProcTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    BLLFactory <Apply> .Instance.Update(applyInfo, applyId);
                }

                #region 记录到流程日志

                var flowLogInfo = new ApplyFlowlogInfo(applyId, flowInfo.FlowName, userInfo.ID.ToInt32(), opinion, applyInfo.ProcType);
                flowLogInfo.FlowId  = flowInfo.ID;
                flowLogInfo.OrderNo = flowInfo.OrderNo;
                BLLFactory <ApplyFlowlog> .Instance.Insert(flowLogInfo);

                #endregion
            }
        }
 public ActionResult SaveForm(string keyValue, s_application_settingEntity entity)
 {
     entity.F_ApplicationId = LoginUserInfo.Get().userId;
     application_SettingIBLL.SaveEntity(keyValue, entity);
     return(Success("保存成功!"));
 }
Ejemplo n.º 33
0
        public TaskCollectionData ReadTaskData(Stream stream, List <Model.TemplateConfig> configs, List <TemplateSheet> sheetConfigs)
        {
            LoginUserInfo userinfo = WebHelper.GetCurrentUser();;

            Workbook           dataBook = new Workbook(stream);
            TaskCollectionData tcd      = new TaskCollectionData();

            tcd.Sheets = new List <DataSheet>();
            StringBuilder sb = new StringBuilder();

            sheetConfigs.ForEach(sheetconfig =>
            {
                DataSheet sheet  = new DataSheet();
                sheet.SheetName  = sheetconfig.TemplateSheetName;
                sheet.Rows       = new List <DataRows>();
                var firstRow     = sheetconfig.RowNum;
                var firstColumn  = sheetconfig.ColumnNum;
                var currentSheet = dataBook.Worksheets[sheet.SheetName];
                if (currentSheet != null)
                {
                    var currentConfigs = configs.FindAll(x => x.TemplateSheetID == sheetconfig.ID).OrderBy(x => x.SortIndex).ToList();
                    for (int i = 0; i <= currentSheet.Cells.MaxDataRow; i++)
                    {
                        if (i >= firstRow)
                        {
                            DataRows dr = new DataRows();
                            dr.Cells    = new List <RowCells>();
                            //获取数据
                            for (int j = 0; j <= currentSheet.Cells.MaxDataColumn; j++)
                            {
                                if (j >= firstColumn - 1)
                                {
                                    int cellIndex = j - (firstColumn - 1);
                                    RowCells cell = new RowCells();
                                    cell.Index    = cellIndex;
                                    if (currentConfigs.Count >= cellIndex + 1)
                                    {
                                        var config     = currentConfigs[cellIndex];
                                        var cellValue  = GetCellValue(currentSheet, i, j, config);
                                        cell.Type      = config.FieldType;
                                        cell.Formula   = config.CellFormula;
                                        cell.IsFormula = currentSheet.Cells[i, j].IsFormula;
                                        cell.Value     = cellValue;
                                        dr.Cells.Add(cell);
                                    }
                                }
                            }
                            if (dr.Cells.Count == 0 || !dr.Cells.Any(x => !string.IsNullOrEmpty(x.Value)))
                            {
                                goto BreakLoop;
                            }
                            var hasError = dr.Cells.FindAll(cell =>
                            {
                                var config = currentConfigs[cell.Index];
                                return(config != null && config.IsRequired == 1 && string.IsNullOrEmpty(cell.Value));
                            })
                                           .Select(cell =>
                            {
                                var config = currentConfigs[cell.Index];
                                return(config);
                            })
                                           .ToList();
                            if (hasError.Count > 0)
                            {
                                sb.AppendLine(string.Format("【{1}】数据列:【{0}】为必填列", string.Join(",", hasError.GroupBy(c => c.FieldName).Select(c => c.Key)), currentSheet.Name));
                            }
                            sheet.Rows.Add(dr);
                        }
                        continue;
                        BreakLoop:
                        {
                            break;
                        }
                    }
                    tcd.Sheets.Add(sheet);
                }
            });
            if (sb.Length > 0)
            {
                sb.AppendLine("请仔细核对");
                throw new Exception(sb.ToString());
            }
            var noDataSheets = tcd.Sheets.Where(t => !t.Rows.Any()).ToList();

            if (noDataSheets.Any())
            {
                throw new Exception(string.Format("【{0}】未检测到有效数据行", string.Join("、", noDataSheets.Select(s => s.SheetName))));
            }
            return(tcd);
        }
Ejemplo n.º 34
0
        public TemplateTask StartCollectTask(string flowCode, string taskTitle, TemplateConfigInstance configInstance, DataCollectUser dUsers, LoginUserInfo wdUser)
        {
            var          currentUser = UserInfoOperator.Instance.GetWDUserInfoByLoginName(wdUser.LoginName);
            TemplateTask task        = new TemplateTask();

            task.ID = Guid.NewGuid().ToString();
            task.DataCollectUserID        = dUsers.ID;
            task.EmployeeCode             = currentUser.EmployeeCode;
            task.OrgID                    = currentUser.OrgID;
            task.OrgName                  = currentUser.UnitName;
            task.EmployeeLoginName        = currentUser.LoginName;
            task.EmployeeName             = currentUser.CNName;
            task.TemplateConfigInstanceID = configInstance.ID;
            task.Status                   = (int)Lib.Common.ProcessStatus.Draft;
            task.CreateDate               = DateTime.Now;
            task.CreatorLoginName         = WebHelper.GetCurrentUser().LoginName;
            task.CreatorName              = WebHelper.GetCurrentUser().CNName;
            task.IsDeleted                = false;
            task.ModifierLoginName        = WebHelper.GetCurrentUser().LoginName;
            task.ModifierName             = WebHelper.GetCurrentUser().CNName;
            task.ModifyTime               = DateTime.Now;


            Employee startUser = new Employee {
                LoginName = currentUser.LoginName
            };
            Employee lastUser = new Employee {
                LoginName = configInstance.UserName
            };
            var         data         = new { flowCode = flowCode, taskID = task.ID, startUser = startUser, lastUser = lastUser, taskTitle = taskTitle, approvalContent = "" };
            var         json         = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            AutoProcess _autoprocess = new AutoProcess()
            {
                BusinessType = "StartProcess",
                BusinessID   = task.ID,
                Parameters   = json
            };

            AutoProcessOperator.Instance.AddAutoproces(_autoprocess);
            //WorkFlowUtil.StartProcess(flowCode, task.ID, startUser, lastUser, taskTitle, "");
            TemplateTaskOperator.Instance.AddModel(task);
            return(task);
        }