Пример #1
0
        /// <summary>
        /// IExceptionFilter接口会要求实现OnException方法,当系统发生未捕获异常时就会触发这个方法。
        /// OnException方法有一个ExceptionContext异常上下文,其中包含了具体的异常信息,HttpContext及mvc路由信息。
        /// 系统一旦出现未捕获异常后,比较常见的做法就是使用日志工具,将异常的详细信息记录下来,方便调试
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            MsgModel msgModel;
            var      exception = context.Exception;

            if (exception is CustomException)
            {
                var customException = exception as CustomException;
                msgModel = MsgModel.Fail(customException.Code, customException.Msg);
            }
            else
            {
                msgModel = MsgModel.Fail(exception.Message);
            }

            //if (_env.IsDevelopment())
            //{
            //    json.message = context.Exception.StackTrace;// 堆栈信息
            //}

            context.Result = new InternalServerErrorObjectResult(msgModel);
            // 采用Serilog日志框架记录
            _logger.LogError(msgModel.message, WriteLog(msgModel.message, exception));
            context.ExceptionHandled = true;
        }
Пример #2
0
        /// <summary>
        /// 新增数据字典项
        /// </summary>
        /// <param name="sys_Dict"></param>
        public MsgModel Add(sys_dict sys_Dict)
        {
            sys_Dict.id = new Snowflake().GetId();
            var result = _baseSysDictService.AddRange(sys_Dict);

            return(result ? MsgModel.Success("新增数据字典项成功!") : MsgModel.Fail("新增数据字典项失败!"));
        }
Пример #3
0
        public MsgModel DeleteMenu(sys_menu sys_menu)
        {
            //查找被删除节点的子节点
            List <sys_menu> myChilds = _baseSysMenuService.GetModels(a => a.menu_pids.Contains("[" + sys_menu.id + "]")).ToList();

            if (myChilds.Count > 0)
            {
                // "不能删除含有下级菜单的菜单"
                return(MsgModel.Fail("不能删除含有下级菜单的菜单"));
            }
            //查找被删除节点的父节点
            List <sys_menu> myFatherChilds = _baseSysMenuService.GetModels(a => a.menu_pids.Contains("[" + sys_menu.menu_pid + "]")).ToList();

            //我的父节点只有我这一个子节点,而我还要被删除,更新父节点为叶子节点。
            if (myFatherChilds.Count == 1)
            {
                sys_menu parent = _baseSysMenuService.GetModels(a => a.id == sys_menu.menu_pid).SingleOrDefault();
                parent.id      = sys_menu.menu_pid;
                parent.is_leaf = true;//更新父节点为叶子节点。
                _baseSysMenuService.Update(parent);
            }
            // 删除节点
            _baseSysMenuService.Remove(sys_menu);
            return(MsgModel.Success("删除菜单项成功!"));
        }
Пример #4
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public MsgModel Login(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return(MsgModel.Fail("用户名或密码为空!"));
            }
            // 加密登陆密码
            string encodePassword = PasswordEncoder.Encode(password);

            sys_user sys_user = _baseService.GetModels(a => a.username == username && a.password == encodePassword).SingleOrDefault();

            if (sys_user == null)
            {
                return(MsgModel.Fail("用户名或密码不正确!"));
            }
            else if (sys_user.enabled == false)
            {
                return(MsgModel.Fail("账户已被禁用!"));
            }

            // 将一些个人数据写入token中
            var customClaims = new List <Claim>
            {
                new Claim(ClaimAttributes.UserId, Convert.ToString(sys_user.id)),
                new Claim(ClaimAttributes.UserName, username)
            };

            var data = _jwtHelper.IssueJwt(customClaims);

            return(MsgModel.Success((object)data));
        }
Пример #5
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public MsgModel Login(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return(MsgModel.Fail("用户名或密码为空!"));
            }
            // 加密登陆密码
            string encodePassword = PasswordEncoder.Encode(password);

            sys_user sys_user = _baseService.GetModels(a => a.username == username && a.password == encodePassword).SingleOrDefault();

            if (sys_user == null)
            {
                return(MsgModel.Fail("用户名或密码不正确!"));
            }
            else if (sys_user.enabled == false)
            {
                return(MsgModel.Fail("账户已被禁用!"));
            }

            // 将一些个人数据写入token中
            var dict = new Dictionary <string, object>
            {
                { ClaimAttributes.UserId, sys_user.id },
                { ClaimAttributes.UserName, username }
            };

            var data = JwtHelper.IssueJwt(dict);

            return(MsgModel.Success((object)data));
        }
Пример #6
0
        public MsgModel AddConfig(sys_config sys_Config)
        {
            sys_Config.id = new Snowflake().GetId();
            var result = _baseSysConfigService.AddRange(sys_Config);

            return(result ? MsgModel.Success("新增配置成功!") : MsgModel.Fail("新增配置失败!"));
        }
Пример #7
0
 public MsgModel DeleteRole(int id)
 {
     if (!_baseSysRoleService.DeleteRange(_baseSysRoleService.GetModels(a => a.id == id)))
     {
         return(MsgModel.Fail("删除角色失败!"));
     }
     return(MsgModel.Success("删除角色成功!"));
 }
Пример #8
0
 /// <summary>
 /// 用户管理:修改
 /// </summary>
 /// <param name="sys_user"></param>
 public MsgModel UpdateUser(sys_user sys_user)
 {
     if (!_baseSysUserService.UpdateRange(sys_user))
     {
         return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "更新用户失败!"));
     }
     return(MsgModel.Success("更新用户成功"));
 }
Пример #9
0
 /// <summary>
 /// 用户管理:删除
 /// </summary>
 /// <param name="userId"></param>
 public MsgModel DeleteUser(long userId)
 {
     if (!_baseSysUserService.DeleteRange(_baseSysUserService.GetModels(a => a.id == userId)))
     {
         return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "删除用户失败!"));
     }
     return(MsgModel.Success("删除用户成功!"));
 }
Пример #10
0
 public MsgModel UpdateRole(sys_role sys_role)
 {
     if (!_baseSysRoleService.Update(sys_role))
     {
         return(MsgModel.Fail("角色更新失败!"));
     }
     return(MsgModel.Success("角色更新成功!"));
 }
Пример #11
0
        /// <summary>
        /// 用户管理:更新用户的激活状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enabled"></param>
        public MsgModel UpdateEnabled(long id, bool enabled)
        {
            sys_user sys_user = _baseSysUserService.GetModels(a => a.id == id).SingleOrDefault();

            sys_user.enabled = enabled;
            bool result = _baseSysUserService.UpdateRange(sys_user);

            return(result ? MsgModel.Success("用户状态更新成功!") : MsgModel.Fail("用户状态更新失败!"));
        }
Пример #12
0
        /// <summary>
        /// 角色管理:更新角色的禁用状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        public MsgModel UpdateStatus(int id, bool status)
        {
            sys_role sys_role = _baseSysRoleService.GetModels(a => a.id == id).SingleOrDefault();

            sys_role.status = status;
            bool result = _baseSysRoleService.Update(sys_role);

            return(result ? MsgModel.Success("角色禁用状态更新成功!") : MsgModel.Fail("角色禁用状态更新失败!"));
        }
Пример #13
0
        public MsgModel UpdateOrg(sys_org sys_org)
        {
            if (!_baseSysOrgService.Update(sys_org))
            {
                return(MsgModel.Fail("更新组织机构失败!"));
            }

            return(MsgModel.Success("更新组织机构成功!"));
        }
Пример #14
0
        /// <summary>
        /// 组织管理:更新组织的禁用状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        public MsgModel UpdateStatus(int id, bool status)
        {
            sys_org sys_org = _baseSysOrgService.GetModels(a => a.id == id).SingleOrDefault();

            sys_org.status = status;
            bool result = _baseSysOrgService.Update(sys_org);

            return(result ? MsgModel.Success("更新组织机构状态成功!") : MsgModel.Fail("更新组织机构状态失败!"));
        }
Пример #15
0
        /// <summary>
        /// 菜单管理:更新菜单的禁用状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        public MsgModel UpdateStatus(int id, bool status)
        {
            sys_menu sys_menu = _baseSysMenuService.GetModels(a => a.id == id).SingleOrDefault();

            sys_menu.id     = id;
            sys_menu.status = status;
            var result = _baseSysMenuService.Update(sys_menu);

            return(result ? MsgModel.Success("菜单禁用状态更新成功!") : MsgModel.Fail("菜单禁用状态更新失败!"));
        }
Пример #16
0
 public MsgModel AddRole(sys_role sys_role)
 {
     sys_role.status = false;// 是否禁用:false
     if (_baseSysRoleService.GetModels(a => a.role_code == sys_role.role_code).Any())
     {
         return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "角色编码已存在,不能重复!"));
     }
     if (!_baseSysRoleService.Insert(sys_role))
     {
         return(MsgModel.Fail("新增角色失败!"));
     }
     return(MsgModel.Success("新增角色成功!"));
 }
Пример #17
0
        /// <summary>
        /// 个人中心:修改密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="oldPass"></param>
        /// <param name="newPass"></param>
        public MsgModel ChangePwd(string userName, string oldPass, string newPass)
        {
            sys_user sys_user = _baseSysUserService.GetModels(a => a.username == userName).SingleOrDefault();
            // 判断旧密码是否正确
            bool isMatch = PasswordEncoder.IsMatch(sys_user.password, oldPass);

            if (!isMatch)
            {
                return(MsgModel.Fail("原密码输入错误,请确认后重新输入!"));
            }
            sys_user.password = PasswordEncoder.Encode(newPass);
            var result = _baseSysUserService.UpdateRange(sys_user);

            return(result ? MsgModel.Success("密码修改成功!") : MsgModel.Fail("密码修改失败!"));
        }
Пример #18
0
        /// <summary>
        /// 用户管理:重置密码
        /// </summary>
        /// <param name="userId"></param>
        public MsgModel PwdReset(long userId)
        {
            sys_user sys_user = _baseSysUserService.GetModels(a => a.id == userId).ToList().SingleOrDefault();

            sys_user.id       = userId;
            sys_user.password = PasswordEncoder.Encode(_sysConfigService.GetConfigItem("user.init.password"));
            var  length = sys_user.password.Length;
            bool result = _baseSysUserService.UpdateRange(sys_user);

            if (!result)
            {
                return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "密码重置失败!"));
            }
            return(MsgModel.Success("密码重置成功!"));
        }
Пример #19
0
        public async Task <IActionResult> RefreshToken()
        {
            var httpContext = _accessor.HttpContext;
            //获取请求头部信息token
            var result = httpContext.Request.Headers.TryGetValue("Authorization", out StringValues oldToken);

            //判断token是否为空
            if (!result || !oldToken.ToString().StartsWith("ey"))
            {
                return(Ok(await Task.FromResult(MsgModel.Fail(StatusCodes.Status401Unauthorized, "用户登录信息已失效,请重新登录!"))));
            }
            string refreshToken = JwtHelper.RefreshToken(oldToken);

            return(Ok(await Task.FromResult(MsgModel.Success((object)refreshToken))));
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
                             .SelectMany(v => v.Errors)
                             .Select(v => v.ErrorMessage)
                             .ToList();

                context.Result = new JsonResult(MsgModel.Fail(errors.FirstOrDefault()))
                {
                    StatusCode = 400
                };
            }
        }
Пример #21
0
 /// <summary>
 /// 用户管理:新增
 /// </summary>
 /// <param name="sys_user"></param>
 public MsgModel AddUser(sys_user sys_user)
 {
     sys_user.password    = PasswordEncoder.Encode(_sysConfigService.GetConfigItem("user.init.password"));
     sys_user.create_time = DateTime.Now; //创建时间
     sys_user.enabled     = true;         //新增用户激活
     if (_baseSysUserService.GetModels(a => a.username == sys_user.username).Any())
     {
         return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "用户名已存在,不能重复"));
     }
     if (!_baseSysUserService.Insert(sys_user))
     {
         return(MsgModel.Fail("新增用户失败!"));
     }
     return(MsgModel.Success("新增用户成功!"));
 }
Пример #22
0
        public async Task <IActionResult> RefreshToken()
        {
            var httpContext = _accessor.HttpContext;
            //获取请求头部信息token
            var result       = httpContext.Request.Headers.TryGetValue("Authorization", out StringValues oldToken);
            var isValidToken = new JwtSecurityTokenHandler().CanReadToken(oldToken);

            //判断token是否为空
            if (!result || !isValidToken || !_jwtHelper.Validate(oldToken))
            {
                return(Ok(await Task.FromResult(MsgModel.Fail(StatusCodes.Status401Unauthorized, "用户登录信息已失效,请重新登录!"))));
            }
            string refreshToken = _jwtHelper.RefreshToken(oldToken);

            return(Ok(await Task.FromResult(MsgModel.Success((object)refreshToken))));
        }
Пример #23
0
        public MsgModel AddRole(sys_role sys_role)
        {
            CustomException customException = new CustomException();

            sys_role.id     = new Snowflake().GetId();
            sys_role.status = false;// 是否禁用:false
            if (_baseSysRoleService.GetModels(a => a.role_code == sys_role.role_code).Any())
            {
                customException.Code = (int)HttpStatusCode.Status500InternalServerError;

                return(MsgModel.Fail(StatusCodes.Status500InternalServerError, "角色编码已存在,不能重复!"));
            }
            if (!_baseSysRoleService.AddRange(sys_role))
            {
                return(MsgModel.Fail("新增角色失败!"));
            }
            return(MsgModel.Success("新增角色成功!"));
        }
Пример #24
0
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private async Task HandleException(HttpContext context, Exception exception)
        {
            context.Response.StatusCode  = 500;
            context.Response.ContentType = "text/json;charset=utf-8;";
            MsgModel msgModel;

            if (exception is CustomException)
            {
                var customException = exception as CustomException;
                msgModel = MsgModel.Fail(customException.Code, customException.Msg);
            }
            else
            {
                msgModel = MsgModel.Fail(exception.Message);
            }

            // 采用Serilog日志框架记录
            _logger.LogError(msgModel.message, WriteLog(msgModel.message, exception));
            await context.Response.WriteAsync(JsonConvert.SerializeObject(msgModel));
        }
Пример #25
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public MsgModel SignUp(SysUser user)
        {
            var dict         = new Dictionary <string, object>();
            var stringRandom = StringHelper.GenerateRandom(10);

            user.username = stringRandom;
            //user.nickname = stringRandom;
            if (user.phone != null)
            {
                var queryUser = _baseService.GetModels(a => a.phone == user.phone).SingleOrDefault();
                if (queryUser == null)
                {
                    var sysUser = new sys_user();
                    sysUser = user.BuildAdapter().AdaptToType <sys_user>();
                    _baseService.AddRange(sysUser);

                    var customClaims = new List <Claim>
                    {
                        new Claim(ClaimAttributes.UserId, Convert.ToString(queryUser.id)),
                        new Claim(ClaimAttributes.UserName, queryUser.username)
                    };

                    var token = _jwtHelper.IssueJwt(customClaims);
                    dict.Add("token", token);
                    return(MsgModel.Success(dict));
                }
                else
                {
                    var userDto = new SysUser();
                    userDto = queryUser.BuildAdapter().AdaptToType <SysUser>();
                    // 用户存在直接登录
                    return(Login(userDto.username, userDto.password));
                }
            }
            else
            {
                return(MsgModel.Fail("参数格式错误!"));
            }
        }
Пример #26
0
        /// <summary>
        /// 单文件文件上传
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <MsgModel> UploadAsync(FileUploadModel model, CancellationToken cancellationToken = default)
        {
            var result = new MsgModel();

            if (model.FormFile == null || model.FormFile.Length < 1)
            {
                if (model.Request.Form.Files != null && model.Request.Form.Files.Any())
                {
                    model.FormFile = model.Request.Form.Files[0];
                }
            }

            if (model.FormFile == null || model.FormFile.Length < 1)
            {
                return(MsgModel.Fail("请选择文件!"));
            }

            var name     = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;
            var size     = model.FormFile.Length;
            var fileInfo = new FileInfo(name, size);

            if (model.MaxSize > 0 && model.MaxSize < size)
            {
                return(MsgModel.Fail($"文件大小不能超过{new FileSize(model.MaxSize)}"));
            }

            if (model.LimitExt != null && !model.LimitExt.Any(m => m.EqualsIgnoreCase(fileInfo.Ext)))
            {
                return(MsgModel.Fail($"文件格式无效,请上传{model.LimitExt.Aggregate((x, y) => x + "," + y)}格式的文件"));
            }

            var date = DateTime.Now;

            fileInfo.Path = Path.Combine(model.RelativePath, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));
            var resultModel = await UploadSave(model.FormFile, fileInfo, model.RootPath, model.CalcMd5, cancellationToken);

            return(MsgModel.Success(resultModel));
        }
Пример #27
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public MsgModel SignUp(SysUser user)
        {
            var dict         = new Dictionary <string, object>();
            var stringRandom = CommonUtils.GetStringRandom(10);

            user.username = stringRandom;
            //user.nickname = stringRandom;
            if (user.phone != null)
            {
                var queryUser = _baseService.GetModels(a => a.phone == user.phone).SingleOrDefault();
                if (queryUser == null)
                {
                    var sysUser = new sys_user();
                    sysUser = user.BuildAdapter().AdaptToType <sys_user>();
                    _baseService.Add(sysUser);
                    var playLoad = new Dictionary <string, object>
                    {
                        { ClaimAttributes.UserId, queryUser.id },
                        { ClaimAttributes.UserName, queryUser.username }
                    };

                    var token = JwtHelper.IssueJwt(playLoad);
                    dict.Add("token", token);
                    return(MsgModel.Success(dict));
                }
                else
                {
                    var userDto = new SysUser();
                    userDto = queryUser.BuildAdapter().AdaptToType <SysUser>();
                    // 用户存在直接登录
                    return(Login(userDto.username, userDto.password));
                }
            }
            else
            {
                return(MsgModel.Fail("参数格式错误!"));
            }
        }
Пример #28
0
        public MsgModel DeleteConfig(long configId)
        {
            var result = _baseSysConfigService.DeleteRange(_baseSysConfigService.GetModels(a => a.id == configId));

            return(result ? MsgModel.Success("删除配置成功!") : MsgModel.Fail("删除配置失败!"));
        }
Пример #29
0
        public MsgModel AddConfig(sys_config sys_Config)
        {
            var result = _baseSysConfigService.Insert(sys_Config);

            return(result ? MsgModel.Success("新增配置成功!") : MsgModel.Fail("新增配置失败!"));
        }
Пример #30
0
        public MsgModel UpdateConfig(sys_config sys_Config)
        {
            var result = _baseSysConfigService.Update(sys_Config);

            return(result ? MsgModel.Success("更新配置成功!") : MsgModel.Fail("更新配置失败!"));
        }