Esempio n. 1
0
        /// <summary>
        /// 保存验证处理
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logonInfo"></param>
        protected override void SavingCheck(IndustryInfo info, TokenLogonInfo logonInfo)
        {
            //行业名称不能为空
            if (string.IsNullOrWhiteSpace(info.Name))
            {
                throw ApiException.BadRequest("行业名称不能为空");
            }
            //行业名称不能重复
            var query = _Dal.Queryable().Where(e => e.Name == info.Name).ToList();

            if (!info.IsEmpty)//修改时过滤本身的ID
            {
                string id = info.Id.ToString();
                for (int i = 0; i < query.Count; i++)
                {
                    if (query[i].Id.ToString() == id)
                    {
                        query.RemoveAt(i);
                        break;
                    }
                }
            }
            if (query.Count() > 0)
            {
                throw ApiException.BadRequest("行业名称不能重复");
            }
        }
        /// <summary>
        /// 访问接口时 完善用户权限
        /// </summary>
        /// <param name="identity"></param>
        public void FillFunctionPolicy(ClaimsIdentity identity)
        {
            RoleView role = new RoleView();

            // 如果有获取角色的委托方法,使用委托方法
            if (OnLoadRole != null)
            {
                role = OnLoadRole(identity);
            }
            else
            {
                // 暂不添加游客的角色获取逻辑
            }

            // 添加权限声明
            if (role == null)
            {
                throw ApiException.BadRequest("无法根据用户获取角色信息");
            }
            if (role.FunctionPower.Count == 0)
            {
                throw ApiException.BadRequest("您没有任何权限,请与管理员联系");
            }
            foreach (var function in role.FunctionPower)
            {
                identity.AddClaim(new Claim("function_policy", function.Policy));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string Login(string account, string password)
        {
            account  = account.Trim();
            password = password.Trim();
            //查询密码正确的可用用户列表
            var pwdQuery = _employeeDal.Queryable().Where(e => e.LogonPassword == password && e.IsDelete == false).ToList();

            // 通过账号和密码验证登录
            var employeeList = pwdQuery.Where(e => e.LogonAccount == account);

            if (employeeList.Count() > 1)
            {
                throw ApiException.BadRequest("有多个满足条件的用户,无法登陆。");
            }

            // 如果查找不到用户信息,并且允许用电话登录,尝试电话号码+登录密码登录
            if (employeeList.Count() == 0 && AuthServiceOption.Option.IsLogonByTelephone)
            {
                employeeList = pwdQuery.Where(e => e.Telephone == account || e.Mobile == account);
                if (employeeList.Count() > 1)
                {
                    throw ApiException.BadRequest("有多个满足条件的用户,无法通过电话登陆。");
                }
            }

            var employee = employeeList.FirstOrDefault();

            if (employee == null)
            {
                throw ApiException.BadRequest("您的登陆账号或密码错误。");
            }

            if (employee.State == UserState.Disable)
            {
                throw ApiException.BadRequest("您的登陆功能已被禁用,请与管理员联系。");
            }
            if (employee.State == UserState.LogonLock)
            {
                throw ApiException.BadRequest("多次登陆失败,登陆已被锁住,请与管理员联系。");
            }

            // 执行扩展的登录事件
            OnLogin?.Invoke(employee);

            List <Claim> claims = new List <Claim>
            {
                new Claim("id", employee.Id.ToString()),
                new Claim("name", employee.Name ?? ""),
                new Claim("roleId", employee.Role?.Id ?? ""),
                new Claim("depId", employee.Department?.Id ?? ""),
                new Claim("depName", employee.Department?.Name ?? ""),
                new Claim("type", "AuthService")
            };


            var    identity = new ClaimsIdentity(new GenericIdentity(account, "Token"), claims);
            string token    = Jwt.GenerateJwtToken(account, identity, _tokenOptions);

            return(token);
        }
        /// <summary>
        /// 保存的校验
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logonInfo"></param>
        protected override void SavingCheck(IndustryCategoryInfo info, TokenLogonInfo logonInfo)
        {
            //数据验证
            if (string.IsNullOrWhiteSpace(info.Name))
            {
                throw ApiException.BadRequest("行业分类名称不能为空");
            }

            //检查行业名称不能重复
            var query = _Dal.Queryable().Where(e => !string.IsNullOrEmpty(e.Name) && e.Name.Equals(info.Name) && e.IsDelete == false);

            if (info.IsEmpty)
            {
                if (query.Count() > 0)
                {
                    throw ApiException.BadRequest("行业分类不能重复");
                }
            }
            else
            {
                string id = info.Id.ToString();
                foreach (var item in query)
                {
                    if (item.Id.ToString() != id)
                    {
                        throw ApiException.BadRequest("行业分类不能重复");
                    }
                }
            }
        }
 /// <summary>
 /// 保存的前置校验
 /// </summary>
 /// <param name="info"></param>
 /// <param name="logonInfo"></param>
 protected override void SavingCheck(EmailConfigInfo info, TokenLogonInfo logonInfo)
 {
     #region 验证非空
     if (string.IsNullOrWhiteSpace(info.LocalMailFromName))
     {
         throw ApiException.BadRequest("邮箱标题不允许为空");
     }
     if (string.IsNullOrWhiteSpace(info.LocalMailFromMail))
     {
         throw ApiException.BadRequest("邮箱不能为空");
     }
     if (string.IsNullOrWhiteSpace(info.LocalMailSMTP))
     {
         throw ApiException.BadRequest("SMTP 服务器不能为空");
     }
     if (string.IsNullOrWhiteSpace(info.LocalMailSMTPPort))
     {
         throw ApiException.BadRequest("SMTP 服务器端口不能为空");
     }
     if (string.IsNullOrWhiteSpace(info.LocalMailUserName))
     {
         throw ApiException.BadRequest("邮箱的用户名不能为空");
     }
     if (string.IsNullOrWhiteSpace(info.LocalMailPwd))
     {
         throw ApiException.BadRequest("邮箱的密码或授权密钥不能为空");
     }
     #endregion
 }
Esempio n. 6
0
        public async Task <ActionResult> UpdateAsync(int userId, [FromBody] UpdateDoorPermissionsRequest request)
        {
            var existingPermissions = await _permissionsRepository.GetDoorPermissionsAsync(userId);

            var toDelete = existingPermissions
                           .Where(p => !request.PermittedDoors.Contains(p.DoorId));

            var toAddIds = request.PermittedDoors
                           .Where(d => existingPermissions.All(p => p.DoorId != d))
                           .ToList();

            var allExist = await _doorsRepository.AllExistAsync(toAddIds);

            if (!allExist)
            {
                throw ApiException.BadRequest("Some doors don't exist");
            }

            var toAdd = toAddIds
                        .Select(d => new DoorPermission
            {
                DoorId = d,
                UserId = userId
            });

            await _permissionsRepository.UpdateDoorPermissionsAsync(new UpdateDoorPermissionsModel
            {
                ToAdd    = toAdd,
                ToDelete = toDelete
            });

            return(Ok());
        }
 /// <summary>
 /// 保存的校验
 /// </summary>
 /// <param name="info"></param>
 /// <param name="logonInfo"></param>
 protected override void SavingCheck(DepartmentInfo info, TokenLogonInfo logonInfo)
 {
     //数据验证
     if (string.IsNullOrWhiteSpace(info.Name))
     {
         throw ApiException.BadRequest("请指定部门的名称");
     }
 }
Esempio n. 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ResultView Send(SingleSendData data)
        {
            SmsSingleSenderResult result = Send(0, "86", data.PhoneNumber, data.Message, "", "");

            if (result.result == 0)
            {
                return(ResultView.Success());
            }
            throw ApiException.BadRequest(result.errMsg);
        }
        /// <summary>
        /// 删除时的检查
        /// </summary>
        /// <param name="info"></param>
        protected override void DeleteRemoveCheck(RoleInfo info)
        {
            //如果角色下有员工信息,不允许删除
            EmployeeService employeeService = ServiceLoader.GetService <EmployeeService>();

            if (employeeService.CountByRoleId(info.Id.ToString()) > 0)
            {
                throw ApiException.BadRequest("角色下有员工信息,不允许删除");
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 保存一个客户端提交的文件
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="file"></param>
        /// <param name="checkFile"></param>
        /// <returns></returns>
        protected UploadFileInfo SaveSingleFile(string fullFileName, IFormFile file, Action <UploadFileInfo, IFormFile> checkFile)
        {
            // 1、检验参数
            // 1.1、获取上传的文件
            if (file == null)
            {
                throw ApiException.BadRequest("上传的文件信息为空");
            }
            // 1.2、文件校验  判断文件大小
            if (file.Length > MaxFileSize)
            {
                throw ApiException.BadRequest($"文件太大,只能上传小于{MaxFileSize}个字节的的文件。");
            }

            // 2、完善数据
            // 2.1、如果文件没有扩展名,根据上传的文件设置
            if (!System.IO.Path.HasExtension(fullFileName))
            {
                fullFileName += System.IO.Path.GetExtension(file.FileName);
            }
            // 2.2、设置上传文件信息
            UploadFileInfo result = new UploadFileInfo
            {
                FileSize       = file.Length,
                WebFileName    = fullFileName.Replace("~/", "").Replace(DiskPath, "").Replace("wwwroot", "").Replace("\\", "/").TrimStart('/'),
                DiskFileName   = fullFileName.Contains("~/") ? DiskPath + fullFileName.Replace("~", "") : fullFileName,
                UploadFileName = file.FileName,
                MainFileName   = System.IO.Path.GetFileNameWithoutExtension(fullFileName),
                ExtFileName    = System.IO.Path.GetExtension(fullFileName)
            };

            result.SaveDiskDirectory = System.IO.Path.GetDirectoryName(result.DiskFileName);

            // 3、文件格式验证
            if (checkFile != null)
            {
                checkFile.Invoke(result, file);
            }

            // 4、保存文件
            // 4.1、设置保存文件的目录
            if (!System.IO.Directory.Exists(result.SaveDiskDirectory))
            {
                System.IO.Directory.CreateDirectory(result.SaveDiskDirectory);
            }
            // 4.2、保存文件
            using (System.IO.FileStream fs = System.IO.File.Create(result.DiskFileName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            //5、返回上传成功的文件信息
            return(result);
        }
Esempio n. 11
0
        /// <summary>
        /// 每次请求接口时,加载用户的权限信息
        /// </summary>
        /// <param name="identity"></param>
        public void FillFunctionPolicy(ClaimsIdentity identity)
        {
            string userId = "";

            foreach (var item in identity.Claims)
            {
                if (item.Type == "id")
                {
                    userId = item.Value;
                    break;
                }
            }


            EmployeeView employee = _EmployeeService.SearchById(userId);

            // 添加角色声明
            //Claim claimRole = new Claim(ClaimTypes.Role, employee.Role.name);
            //identity.AddClaim(claimRole);
            if (employee == null)
            {
                throw ApiException.BadRequest("无法根据Token信息获取用户");
            }
            // 添加权限声明
            RoleView role = _RoleService.SearchById(employee.Role.Id);

            if (role == null)
            {
                throw ApiException.BadRequest("无法根据用户获取角色信息");
            }
            if (role.FunctionPower == null)
            {
                //如果功能点为空,初始化功能点
                if (_FunctionService.SearchQueryable().Count() == 0)
                {
                    //初始化系统菜单
                    _MenuService.Init();
                    //初始化系统功能点列表
                    _FunctionService.Init();
                    //初始化角色信息
                    _RoleService.InitAdmin();
                    //初始化用户信息
                    _EmployeeService.UpdateAdmin();
                }
            }
            if (role.FunctionPower.Count == 0)
            {
                _logger.LogInformation($"{employee.Name}用户无任何功能点权限。所属角色为:{role.Name}({role.Id.ToString()})");
            }
            foreach (var function in role.FunctionPower)
            {
                identity.AddClaim(new Claim("function_policy", function.Policy));
            }
        }
        /// <summary>
        /// 根据持久化对象名称获取数据库操作对象
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public static MongoProvider GetProvider(string typeName)
        {
            if (ProviderDict.Count == 0)
            {
                new MongoLoader().Init();
            }

            if (ProviderDict.ContainsKey(typeName))
            {
                return(ProviderDict[typeName]);
            }
            throw ApiException.BadRequest($"指定的对象{typeName}没有对应的数据库操作服务,请检查DBMapping特性和数据库配置");
        }
Esempio n. 13
0
        /// <summary>
        /// 上传图片操作
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="file"></param>
        static public UploadFileInfo UploadImage(string fullFileName, IFormFile file)
        {
            // 控制上传文件不能大于5M
            UploadFileHandle handle = new UploadFileHandle(1024 * 1024 * 5);

            return(handle.SaveSingleFile(fullFileName, file, (info, f) =>
            {
                // 获取扩展名
                string ext = System.IO.Path.GetExtension(f.FileName);
                //Todo : 先简单判断扩展名,有时间分析下图片格式。
                if (ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".bmp")
                {
                    throw ApiException.BadRequest("图片格式不对");
                }
            }));
        }
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public ResultView UpdatePassword(string id, string oldPwd, string newPwd)
        {
            if (string.IsNullOrWhiteSpace(newPwd.Trim()))
            {
                throw ApiException.BadRequest("请输入新密码");
            }
            var emp = _Dal.SearchById(id);

            if (!emp.LogonPassword.Equals(oldPwd))
            {
                throw ApiException.BadRequest("原密码输入错误");
            }
            emp.LogonPassword = newPwd;
            _Dal.UpdateObject(emp);
            return(ResultView.Success(emp.Id));
        }
Esempio n. 15
0
        /// <summary>
        /// 上传Excel文件
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        static public UploadFileInfo UploadExcel(string fullFileName, IFormFile file)
        {
            // 控制上传文件不能大于50M
            UploadFileHandle handle = new UploadFileHandle(1024 * 1024 * 50);

            return(handle.SaveSingleFile(fullFileName, file, (info, f) =>
            {
                // 获取扩展名
                string ext = System.IO.Path.GetExtension(f.FileName);
                //Todo : 先简单判断扩展名。
                if (ext != ".xlsx")
                {
                    throw ApiException.BadRequest("上传的Excel文件格式不对,需要Office2007以上的版本的Excel文件,扩展名为xlsx。");
                }
            }));
        }
        /// <summary>
        /// 保存前,完善数据
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logonInfo"></param>
        protected override void Saving(DepartmentInfo info, TokenLogonInfo logonInfo)
        {
            //完善上级部门名称
            if (!string.IsNullOrEmpty(info.ParentId))
            {
                var parent = _SearchById(info.ParentId);
                info.ParentName = parent.Name;
                info.ParentsIds = parent.ParentsIds;
                if (!info.IsEmpty)
                {
                    info.ParentsIds.Add(info.Id.ToString());
                }
            }
            else
            {
                info.ParentId   = string.Empty;
                info.ParentName = string.Empty;
                if (info.IsEmpty)
                {
                    info.ParentsIds = new List <string>();
                }
                else
                {
                    info.ParentsIds = new List <string>()
                    {
                        info.Id.ToString()
                    };
                }
            }

            //完善部门主管信息
            //if (!string.IsNullOrEmpty(info.ManageId))
            //{
            //    EmployeeService employeeService = ServiceLoader.GetService<EmployeeService>();
            //    var employee = employeeService._SearchById(info.ManageId);
            //    info.ManageName = employee.Name;
            //}
            //else
            //{
            //    info.ManageName = string.Empty;
            //}
            // 上级部门不能是自己的子部门
            if (!string.IsNullOrEmpty(info.ParentId) && GetSubDepartmentId(info.Id.ToString()).Contains(info.ParentId))
            {
                throw ApiException.BadRequest("上级部门不能是" + info.Name + "的子部门");
            }
        }
        /// <summary>
        /// 保存的前置操作
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logonInfo"></param>
        protected override void Saving(EmployeeInfo info, TokenLogonInfo logonInfo)
        {
            //设置员工状态
            info.State        = UserState.Enable;
            info.ProcessState = ProcessState.Enable;

            //完善数据
            //1、完善部门信息
            if (info.Department != null && !string.IsNullOrWhiteSpace(info.Department.Id))
            {
                string depId = info.Department.Id;
                if (!string.IsNullOrWhiteSpace(depId))
                {
                    DepartmentInfo depInfo = _DepDal.SearchById(depId);
                    if (depInfo == null)
                    {
                        throw ApiException.BadRequest("选择的部门信息不存在,请刷新页面再尝试");
                    }
                    info.Department = new SelectView()
                    {
                        Id = depId, Name = depInfo.Name, Code = depInfo.Code
                    };
                    info.ParentDepartment.Id   = depInfo.ParentId;
                    info.ParentDepartment.Name = depInfo.Name;
                    info.ParentDepartment.Ids  = depInfo.ParentsIds;
                }
            }

            //2、完善角色信息
            if (info.Role != null && !string.IsNullOrWhiteSpace(info.Role.Id))
            {
                string roleId = info.Role.Id;
                if (!string.IsNullOrWhiteSpace(roleId))
                {
                    RoleInfo role = _RoleDal.SearchById(roleId);
                    if (role == null)
                    {
                        throw ApiException.BadRequest("选择的角色信息不存在,请刷新页面再尝试");
                    }
                    info.Role = new SelectView()
                    {
                        Id = roleId, Name = role.Name, Code = ""
                    };
                }
            }
        }
        /// <summary>
        /// 根据id查询对象信息  如果无查询结果会抛出异常
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T _SearchById(IdType id)
        {
            _logger.LogTrace($"根据ID查询对象(_SearchById),对象类型为:[{typeof(T).FullName}]");
            // 检查ID是否有效
            if (!new T().CheckId(id))
            {
                _logger.LogWarning($"按ID查询对象时,ID无效。类型为:[{typeof(T).FullName}][id={id}]");
                throw ApiException.BadRequest("请求的id无效。");
            }
            // 根据ID获取信息
            var info = _Dal.SearchByTypeId(id);

            _logger.LogTrace($"根据ID查询对象,已获取对象。类型为:[{typeof(T).FullName}]\r\n对象值:[{info.ToJson()}]");
            // 查询到Info对象后的事件处理
            OnSearchInfoById?.Invoke(info);
            return(info);
        }
        /// <summary>
        /// 保存的校验
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logonInfo"></param>
        protected override void SavingCheck(EmployeeInfo info, TokenLogonInfo logonInfo)
        {
            // 处理角色的验证
            if (RequiredRole)
            {
                if (info.Role == null)
                {
                    throw ApiException.BadRequest("请指定用户的角色");
                }
            }

            // 处理部门的验证
            if (RequiredDepartment)
            {
                if (info.Department == null)
                {
                    throw ApiException.BadRequest("请指定用户的部门");
                }
            }

            // 验证登录账号
            if (info.IsEmpty)
            {
                if (_Dal.Queryable().Where(e => e.LogonAccount == info.LogonAccount).Count() > 0)
                {
                    throw ApiException.BadRequest("登陆账号已存在,无法新增用户");
                }
            }
            else
            {
                foreach (var item in _Dal.Queryable().Where(e => e.LogonAccount == info.LogonAccount))
                {
                    if (item.Id.ToString() != info.Id.ToString())
                    {
                        throw ApiException.BadRequest("登陆账号已存在,无法修改");
                    }
                }
            }
        }
Esempio n. 20
0
 /// <summary>
 /// 根据id查询对象
 /// </summary>
 /// <returns></returns>
 public T SearchByTypeId(ObjectId id)
 {
     try
     {
         var      result  = MongoCollection.FindAsync(new BsonDocument("_id", id)).Result;
         List <T> objList = result.ToList();
         if (objList.Count == 0)
         {
             MongoLog.Logger.Warning($"按ObjectId查询时,无法找到对象。ObjectId:[{id}]  查询对象类型:[{typeof(T).FullName}]");
         }
         return(objList.FirstOrDefault());
     }
     catch (System.TimeoutException te)
     {
         MongoLog.Logger.Warning(te, "数据库链接超时。链接字符串:" + Provider.Connection.ConnectionString());
         throw ApiException.BadRequest("连接数据库超时,请稍后再试");
     }
     catch (AggregateException ae)
     {
         ae.Handle((x) =>
         {
             if (x is TimeoutException)
             {
                 MongoLog.Logger.Warning(x, "数据库链接超时。链接字符串:" + Provider.Connection.ConnectionString());
                 throw ApiException.BadRequest("连接数据库超时,请稍后再试");
             }
             return(false);
         });
         throw;
     }
     catch (Exception ex)
     {
         MongoLog.Logger.Warning(ex, "操作异常终止。");
         throw;
     }
 }