コード例 #1
0
        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <returns></returns>
        private Task ClearCache()
        {
            var task1 = _cacheHandler.RemoveAsync(CacheKeys.DEPARTMENT_TREE);
            var task2 = _cacheHandler.RemoveAsync(CacheKeys.EMPLOYEE_TREE);

            return(Task.WhenAll(task1, task2));
        }
コード例 #2
0
ファイル: AccountService.cs プロジェクト: windtone/NetModular
        public void ClearPermissionListCache(Guid id)
        {
            var list = EnumExtensions.ToResult <Platform>();

            foreach (var option in list)
            {
                _cache.RemoveAsync(string.Format(CacheKeys.AccountPermissions, id, option.Value.ToInt())).Wait();
            }
        }
コード例 #3
0
ファイル: AccountService.cs プロジェクト: yh-test/NetModular
        public void ClearPermissionListCache(Guid id)
        {
            var list = EnumExtensions.ToResult <Platform>();

            foreach (var option in list)
            {
                _cache.RemoveAsync($"{CacheKeys.ACCOUNT_PERMISSIONS}:{id}:{option.Value.ToInt()}").Wait();
            }
        }
コード例 #4
0
        public async Task <ResultModel <AccountEntity> > Login(LoginModel model)
        {
            var result = new ResultModel <AccountEntity>();

            var verifyCodeKey = CacheKeys.VerifyCodeKey + model.PictureId;
            var systemConfig  = (await _systemService.GetConfig()).Data;

            if (systemConfig.LoginVerifyCode)
            {
                if (model.Code.IsNull())
                {
                    return(result.Failed("请输入验证码"));
                }

                var code = await _cache.GetAsync(verifyCodeKey);

                if (model.PictureId.IsNull() || !model.Code.Equals(code))
                {
                    return(result.Failed("验证码有误"));
                }
            }

            var account = await _accountRepository.GetByUserName(model.UserName, model.AccountType);

            if (account == null || account.Deleted)
            {
                return(result.Failed("账户不存在"));
            }

            var password = EncryptPassword(account.UserName.ToLower(), model.Password);

            if (!account.Password.Equals(password))
            {
                return(result.Failed("密码错误"));
            }

            //检测账户状态
            if (!CheckAccount(account, out string msg))
            {
                return(result.Failed(msg));
            }

            #region ==修改登录信息==

            //是否激活
            var status = account.Status == AccountStatus.Inactive ? AccountStatus.Enabled : AccountStatus.UnKnown;
            await _accountRepository.UpdateLoginInfo(account.Id, model.IP, status);

            #endregion

            //删除验证码缓存
            await _cache.RemoveAsync(verifyCodeKey);

            return(result.Success(account));
        }
コード例 #5
0
        public async Task <ResultModel <LoginResultModel> > Login(LoginModel model, int refreshTokenExpiredTime)
        {
            var result = new ResultModel <LoginResultModel>();

            //检测验证码
            if (model.VerifyCode != null && !await CheckVerifyCode(result, model.VerifyCode))
            {
                return(result);
            }

            //检测用户
            var user = await _userRepository.FirstAsync(m => m.UserCode == model.UserCode && m.IsDel == false);

            var checkUserResult = CheckUser(user);

            if (!checkUserResult.Successful)
            {
                return(result.Failed(checkUserResult.Msg));
            }

            //检测密码
            if (!CheckPassword(result, model, user))
            {
                return(result);
            }

            //更新登录信息
            var loginInfo = await UpdateLoginInfo(user, refreshTokenExpiredTime);

            if (loginInfo == null)
            {
                return(result.Failed("更新登录信息失败"));
            }

            //获取用户角色
            var roles = await _roleUserRepository.QueryByUserId(user.Id);

            //删除验证码缓存
            if (model.VerifyCode != null)
            {
                await _cacheHandler.RemoveAsync(string.Format(CacheKeys.VerifyCodeKey, model.VerifyCode.Id));
            }

            //清除账户的认证信息缓存
            await _cacheHandler.RemoveAsync(string.Format(CacheKeys.UserAuthInfo, user.Id));

            return(result.Success(new LoginResultModel
            {
                User = user,
                AuthInfo = loginInfo,
                RoleIds = string.Join(",", roles.Select(m => m.Id).ToList()),
                RoleCodes = string.Join(",", roles.Select(m => m.RoleCode).ToList()),
                RoleNames = string.Join(",", roles.Select(m => m.RoleName).ToList())
            }));
        }
コード例 #6
0
        private async Task ClearCache(string group, string code)
        {
            if (_options.DictCacheEnabled)
            {
                var selectKey = string.Format(CacheKeys.DictSelect, group.ToUpper(), code.ToUpper());
                var treeKey   = string.Format(CacheKeys.DictTree, group.ToUpper(), code.ToUpper());
                await _cacheHandler.RemoveAsync(selectKey);

                await _cacheHandler.RemoveAsync(treeKey);
            }
        }
コード例 #7
0
        private async Task ClearCache(string group, string code)
        {
            var config = _configProvider.Get <CommonConfig>();

            if (config.DictCacheEnabled)
            {
                var selectKey = $"{CacheKeys.DICT_SELECT}:{group.ToUpper()}_{code.ToUpper()}";
                var treeKey   = $"{CacheKeys.DICT_TREE}:{group.ToUpper()}_{code.ToUpper()}";
                await _cacheHandler.RemoveAsync(selectKey);

                await _cacheHandler.RemoveAsync(treeKey);
            }
        }
コード例 #8
0
        /// <summary>
        /// 更新账户认证信息
        /// </summary>
        protected async Task <LoginResultModel> UpdateAuthInfo(AccountEntity account, LoginModel model, AuthConfig config)
        {
            var authInfo = new AccountAuthInfoEntity
            {
                AccountId               = account.Id,
                Platform                = model.Platform,
                LoginTime               = DateTime.Now.ToTimestamp(),
                LoginIP                 = model.IP,
                RefreshToken            = GenerateRefreshToken(),
                RefreshTokenExpiredTime = DateTime.Now.AddDays(7)//默认刷新令牌有效期7天
            };

            //设置过期时间
            if (config.Jwt.RefreshTokenExpires > 0)
            {
                authInfo.RefreshTokenExpiredTime = DateTime.Now.AddDays(config.Jwt.RefreshTokenExpires);
            }

            Task <bool> task;
            var         entity = await _authInfoRepository.Get(account.Id, model.Platform);

            if (entity != null)
            {
                authInfo.Id = entity.Id;
                task        = _authInfoRepository.UpdateAsync(authInfo);
            }
            else
            {
                task = _authInfoRepository.AddAsync(authInfo);
            }

            if (await task)
            {
                //判断是否开启验证码功能,删除验证码缓存
                if (config.VerifyCode)
                {
                    await _cacheHandler.RemoveAsync(CacheKeys.AUTH_VERIFY_CODE + model.VerifyCode.Id);
                }

                //清除账户的认证信息缓存
                await _cacheHandler.RemoveAsync($"{CacheKeys.ACCOUNT_AUTH_INFO}{account.Id}:{model.Platform.ToInt()}");

                return(new LoginResultModel
                {
                    Account = account,
                    AuthInfo = authInfo
                });
            }

            return(null);
        }
コード例 #9
0
        public Task ClearPermissionListCache(Guid id)
        {
            var list  = EnumExtensions.ToResult <Platform>();
            var tasks = new List <Task>();

            foreach (var t in list)
            {
                tasks.Add(_cache.RemoveAsync($"{CacheKeys.ACCOUNT_PERMISSIONS}{id}:{t.Value.ToInt()}"));
                tasks.Add(_cache.RemoveAsync($"{CacheKeys.ACCOUNT_PAGES}{id}"));
                tasks.Add(_cache.RemoveAsync($"{CacheKeys.ACCOUNT_BUTTONS}{id}"));
                tasks.Add(_cache.RemoveAsync($"{CacheKeys.ACCOUNT_MENUS}{id}"));
            }

            return(Task.WhenAll(tasks));
        }
コード例 #10
0
ファイル: SystemService.cs プロジェクト: xDaWenXi/NetModular
        public IResultModel UpdateConfig(SystemConfigModel model)
        {
            if (model == null)
            {
                return(ResultModel.Failed());
            }

            using (var uow = _dbContext.NewUnitOfWork())
            {
                Update(SystemConfigKey.Title, model.Title, "系统标题", uow).Wait();
                Update(SystemConfigKey.Logo, model.Logo, "系统Logo", uow).Wait();
                Update(SystemConfigKey.Home, model.Home, "系统首页", uow).Wait();
                Update(SystemConfigKey.UserInfoPage, model.UserInfoPage, "个人信息页", uow).Wait();
                Update(SystemConfigKey.ButtonPermission, model.ButtonPermission, "启用按钮权限", uow).Wait();
                Update(SystemConfigKey.PermissionValidate, model.PermissionValidate, "启用权限验证功能", uow).Wait();
                Update(SystemConfigKey.Auditing, model.Auditing, "启用审计日志", uow).Wait();
                Update(SystemConfigKey.ToolbarFullscreen, model.Toolbar.Fullscreen, "显示工具栏全屏按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarSkin, model.Toolbar.Skin, "显示工具栏皮肤按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarLogout, model.Toolbar.Logout, "显示工具栏退出按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarUserInfo, model.Toolbar.UserInfo, "显示工具栏用户信息按钮", uow).Wait();
                Update(SystemConfigKey.CustomCss, model.CustomCss, "自定义CSS样式", uow).Wait();
                Update(SystemConfigKey.MenuUniqueOpened, model.MenuUniqueOpened, "菜单只能打开一个", uow).Wait();
                Update(SystemConfigKey.DialogCloseOnClickModal, model.DialogCloseOnClickModal, "点击模态框关闭对话框", uow).Wait();
                Update(SystemConfigKey.LoginOptionsType, model.LoginOptions.Type, "登录页类型", uow).Wait();
                Update(SystemConfigKey.LoginOptionsVerifyCode, model.LoginOptions.VerifyCode, "启用登录验证码功能", uow).Wait();
                Update(SystemConfigKey.Copyright, model.Copyright, "版权申明", uow).Wait();

                uow.Commit();
            }

            _cache.RemoveAsync(CacheKeys.SystemConfigCacheKey).Wait();

            return(ResultModel.Success());
        }
コード例 #11
0
        public IResultModel UpdateConfig(SystemConfigModel model)
        {
            if (model == null)
            {
                return(ResultModel.Failed());
            }

            using (var uow = _dbContext.NewUnitOfWork())
            {
                Update(SystemConfigKey.Title, model.Title, "系统标题", uow).Wait();
                Update(SystemConfigKey.Logo, model.Logo, "系统Logo", uow).Wait();
                Update(SystemConfigKey.Home, model.Home, "系统首页", uow).Wait();
                Update(SystemConfigKey.UserInfoPage, model.UserInfoPage, "个人信息页", uow).Wait();
                Update(SystemConfigKey.ButtonPermission, model.ButtonPermission, "启用按钮权限", uow).Wait();
                Update(SystemConfigKey.PermissionValidate, model.PermissionValidate, "启用权限验证功能", uow).Wait();
                Update(SystemConfigKey.Auditing, model.Auditing, "启用审计日志", uow).Wait();
                Update(SystemConfigKey.LoginVerifyCode, model.LoginVerifyCode, "启用登录验证码功能", uow).Wait();
                Update(SystemConfigKey.ToolbarFullscreen, model.Toolbar.Fullscreen, "显示工具栏全屏按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarSkin, model.Toolbar.Skin, "显示工具栏皮肤按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarLogout, model.Toolbar.Logout, "显示工具栏退出按钮", uow).Wait();
                Update(SystemConfigKey.ToolbarUserInfo, model.Toolbar.UserInfo, "显示工具栏用户信息按钮", uow).Wait();
                Update(SystemConfigKey.CustomCss, model.CustomCss, "自定义CSS样式", uow).Wait();

                uow.Commit();
            }

            _cache.RemoveAsync(CacheKeys.SystemConfigCacheKey).Wait();

            return(ResultModel.Success());
        }
コード例 #12
0
        /// <summary>
        /// 更新账户认证信息
        /// </summary>
        protected async Task UpdateAuthInfo(LoginResultModel resultModel, LoginModel loginModel)
        {
            resultModel.RefreshToken = GenerateRefreshToken();

            var authInfo = new AccountAuthInfoEntity
            {
                AccountId               = resultModel.AccountId,
                Platform                = resultModel.Platform,
                LoginTime               = resultModel.LoginTime.ToTimestamp(),
                RefreshToken            = resultModel.RefreshToken,
                RefreshTokenExpiredTime = DateTime.Now.AddDays(7)//默认刷新令牌有效期7天
            };


            var config = _configProvider.Get <AuthConfig>();

            //设置过期时间
            if (config.Jwt.RefreshTokenExpires > 0)
            {
                authInfo.RefreshTokenExpiredTime = DateTime.Now.AddDays(config.Jwt.RefreshTokenExpires);
            }

            bool result;
            var  entity = await _authInfoRepository.Get(resultModel.AccountId, resultModel.Platform);

            if (entity != null)
            {
                authInfo.Id = entity.Id;
                result      = await _authInfoRepository.UpdateAsync(authInfo);
            }
            else
            {
                result = await _authInfoRepository.AddAsync(authInfo);
            }

            if (result)
            {
                //判断是否开启验证码功能,删除验证码缓存
                if (config.VerifyCode)
                {
                    await _cacheHandler.RemoveAsync(CacheKeys.AUTH_VERIFY_CODE + loginModel.VerifyCode.Id);
                }

                //清除账户的认证信息缓存
                await _cacheHandler.RemoveAsync($"{CacheKeys.ACCOUNT_AUTH_INFO}{resultModel.AccountId}:{resultModel.Platform.ToInt()}");
            }
        }
コード例 #13
0
        public async Task <IResultModel> Add(PostAddModel model)
        {
            if (await _repository.ExistsName(model.Name))
            {
                return(ResultModel.Failed("名称已存在"));
            }

            var entity = _mapper.Map <PostEntity>(model);

            var result = await _repository.AddAsync(entity);

            if (result)
            {
                await _cacheHandler.RemoveAsync(CacheKeys.POST_SELECT);
            }
            return(ResultModel.Result(result));
        }
コード例 #14
0
        public async Task <IActionResult> PostAsync([FromBody] AuthPost model)
        {
            var result = Unauthorized() as IActionResult;

            var user            = null as ApplicationUser;
            var isAuthenticated = false;

            switch (model.GrantType)
            {
            case GrantType.Password:
                ValidateModelForGrantTypePassword(model);

                user = await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(model.User, model.ClientId.Value);

                if (user != null)
                {
                    await ValidateUserStateAsync(user);

                    var checkPassword = await signInManager.CheckPasswordSignInAsync(user, model.Password);

                    if (checkPassword)
                    {
                        isAuthenticated = true;
                    }
                }

                break;

            case GrantType.RefreshToken:
                ValidateModelForGrantTypeRefreshToken(model);

                if (cacheHandler.TryGetValue <RefreshTokenData>(model.RefreshToken, out var refreshTokenData))
                {
                    await cacheHandler.RemoveAsync <RefreshTokenData>(model.RefreshToken);

                    user = await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(refreshTokenData.UserName, model.ClientId.Value);

                    isAuthenticated = true;
                }

                break;
            }

            if (isAuthenticated)
            {
                var authPostResult = new AuthPostResult(userPrincipalTokenizer.GenerateToken(user));
                await cacheHandler.SetAsync(authPostResult.RefreshToken, new RefreshTokenData()
                {
                    Token    = authPostResult.RefreshToken,
                    UserName = user.UserName
                });

                result = Ok(authPostResult);
            }

            return(result);
        }
コード例 #15
0
        public async Task Remove(string key)
        {
            var cacheKey = CacheDic.FirstOrDefault(m => m.Key.EqualsIgnoreCase(key));

            if (cacheKey.Key.NotNull())
            {
                await _cacheHandler.RemoveAsync(cacheKey.Value);
            }
        }
コード例 #16
0
        /// <summary>
        /// Çå³þ»º´æ
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private async Task ClearCache(AreaEntity entity)
        {
            if (entity.ParentId > 0)
            {
                var parent = await _repository.GetAsync(entity.ParentId);

                if (parent != null)
                {
                    await _cache.RemoveAsync(CacheKeys.Area + parent.Code);
                }
            }
        }
コード例 #17
0
        public async Task <IResultModel> Delete(int id)
        {
            var entity = await _repository.GetAsync(id);

            if (entity == null)
            {
                return(ResultModel.NotExists);
            }

            if (await _itemRepository.ExistsDict(entity.GroupCode, entity.Code))
            {
                return(ResultModel.Failed("请先删除关联的数据项"));
            }

            var result = await _repository.DeleteAsync(id);

            if (result)
            {
                await _cacheHandler.RemoveAsync($"{CacheKeys.DictSelect}{entity.GroupCode.ToUpper()}_{entity.Code.ToUpper()}");
            }
            return(ResultModel.Result(result));
        }
コード例 #18
0
        private void Update <T>(T config)
        {
            var list = new List <ConfigEntity>();

            UpdateConfig(config, list);

            using var uow = _dbContext.NewUnitOfWork();
            var tasks = new Task[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                tasks[i] = _configRepository.UpdateAsync(list[i], uow);
            }

            Task.WaitAll(tasks);
            uow.Commit();

            _cache.RemoveAsync(CacheKeys.SystemConfigCacheKey).GetAwaiter().GetResult();
        }
コード例 #19
0
        public async Task <IResultModel> Add(EmployeeAddModel model)
        {
            if (model.Password.NotNull() && !model.Password.Equals(model.ConfirmPassword))
            {
                return(ResultModel.Failed("两次输入的密码不同"));
            }

            var entity = _mapper.Map <EmployeeEntity>(model);

            entity.JoinDate = entity.JoinDate.Date;

            var account = new AccountAddModel
            {
                Type     = AccountType.User,//使用User账户类型
                UserName = model.UserName,
                Name     = model.Name,
                Password = model.Password,
                IsLock   = true,
                Roles    = model.Roles,
                Status   = AccountStatus.Active
            };

            var result = await _accountService.Add(account);

            if (result.Successful)
            {
                entity.AccountId = result.Data;
                if (await _repository.AddAsync(entity))
                {
                    await _cacheHandler.RemoveAsync(CacheKeys.EMPLOYEE_TREE);

                    return(ResultModel.Success());
                }
            }

            return(result);
        }
コード例 #20
0
ファイル: AuthService.cs プロジェクト: windtone/NetModular
        public async Task <ResultModel <LoginResultModel> > Login(LoginModel model)
        {
            var result = new ResultModel <LoginResultModel>();

            //检测验证码
            if (!await CheckVerifyCode(result, model))
            {
                return(result);
            }

            //检测账户
            var account = await _accountRepository.GetByUserName(model.UserName, model.AccountType);

            var checkAccountResult = CheckAccount(account);

            if (!checkAccountResult.Successful)
            {
                return(result.Failed(checkAccountResult.Msg));
            }

            //检测密码
            if (!CheckPassword(result, model, account))
            {
                return(result);
            }

            using var uow = _dbContext.NewUnitOfWork();

            //判断是否激活,如果未激活需要修改为已激活状态
            if (account.Status == AccountStatus.Inactive)
            {
                if (!await _accountRepository.UpdateAccountStatus(account.Id, AccountStatus.Enabled, uow))
                {
                    return(result.Failed());
                }
            }

            //更新登录信息
            var loginInfo = await UpdateLoginInfo(account, model, uow);

            if (loginInfo != null)
            {
                uow.Commit();

                if (_systemConfig.Login.VerifyCode)
                {
                    //删除验证码缓存
                    await _cacheHandler.RemoveAsync(string.Format(CacheKeys.VerifyCodeKey, model.VerifyCode.Id));
                }

                //清除账户的认证信息缓存
                await _cacheHandler.RemoveAsync(string.Format(CacheKeys.AccountAuthInfo, account.Id, model.Platform.ToInt()));

                return(result.Success(new LoginResultModel
                {
                    Account = account,
                    AuthInfo = loginInfo
                }));
            }

            return(result.Failed());
        }
コード例 #21
0
        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <returns></returns>
        private Task ClearCache()
        {
            var task = _cacheHandler.RemoveAsync(CacheKeys.MENU_TREE);

            return(Task.WhenAll(task));
        }
コード例 #22
0
 public async Task RemoveUserByUserNameAsync(string username) => await cacheHandler.RemoveAsync <ApplicationUser>(username.ToUpper().Trim());
コード例 #23
0
ファイル: SystemService.cs プロジェクト: Ytors/NetModular
        public IResultModel UpdateConfig(SystemConfigModel model)
        {
            if (model == null)
            {
                return(ResultModel.Failed());
            }

            var tasks = new List <Task>();

            _uow.BeginTransaction();

            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Title,
                Value   = model.Title,
                Remarks = "系统标题"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Logo,
                Value   = model.Logo,
                Remarks = "系统Logo"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Home,
                Value   = model.Home,
                Remarks = "系统首页"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.UserInfoPage,
                Value   = model.UserInfoPage,
                Remarks = "个人信息页"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ButtonPermission,
                Value   = model.ButtonPermission.ToString(),
                Remarks = "启用按钮权限"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.Auditing,
                Value   = model.Auditing.ToString(),
                Remarks = "启用审计日志"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.LoginVerifyCode,
                Value   = model.LoginVerifyCode.ToString(),
                Remarks = "启用登录验证码功能"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarFullscreen,
                Value   = model.Toolbar.Fullscreen.ToString(),
                Remarks = "显示工具栏全屏按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarSkin,
                Value   = model.Toolbar.Skin.ToString(),
                Remarks = "显示工具栏皮肤按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarLogout,
                Value   = model.Toolbar.Logout.ToString(),
                Remarks = "显示工具栏退出按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.ToolbarUserInfo,
                Value   = model.Toolbar.UserInfo.ToString(),
                Remarks = "显示工具栏用户信息按钮"
            }));
            tasks.Add(_configRepository.UpdateAsync(new ConfigEntity
            {
                Key     = SystemConfigKey.CustomCss,
                Value   = model.CustomCss,
                Remarks = "自定义CSS样式"
            }));

            Task.WaitAll(tasks.ToArray());

            _uow.Commit();

            _cache.RemoveAsync(SystemConfigCacheKey).Wait();

            return(ResultModel.Success());
        }