/// <summary>
        /// 登录用户验证
        /// </summary>
        /// <param name="account">账户</param>
        /// <param name="password">账户密码</param>
        /// <param name="loginInfo">登录信息</param>
        /// <returns></returns>
        private Result <Account> Login(Account account, string password, string ip)
        {
            //判断用户是否禁止登陆和密码匹配
            if (!account.IsAllowLogin())
            {
                return(Result <Account> .ReFailure(ResultCodes.AccountNotAllowedLogin));
            }
            if (!account.HasPassword(password))
            {
                //获取是否有登录失败信息
                LoginFailed loginFailed = this.GetLoginFailedInfo(account.Username);
                loginFailed.Accumulative();
                if (loginFailed.FailedCount >= this.maxLoginFailedCount)
                {
                    return(Result <Account> .ReFailure(ResultCodes.AccountPasswordNotSameOverrun));
                }
                return(Result <Account> .ReFailure(ResultCodes.AccountPasswordNotSame2.ToFormat((this.maxLoginFailedCount - loginFailed.FailedCount).ToString())));
            }

            //生成访问Token
            List <Claim> claims = new List <Claim>();

            claims.AddRange(new[] {
                new Claim(ClaimTypes.Role, "self"),
                new Claim(ClaimTypes.Role, "admin"),
                new Claim("name", account.Username),
                new Claim("nickname", account.Name),
                new Claim("sub", account.Id.ToString()),
                new Claim("auth_mode", loginType)
            });


            var accessToken = _tokenGenerate.Generate(claims);

            //生成访问Token
            account.SetLoginInfo(new LoginInfo(ip, accessToken));


            //记录登录日志
            this._logLoginRecordService.Record(account, loginType);
            //移除登录失败记录
            this.RemoveLoginFailedInfo(account.Username);
            return(Result <Account> .ReSuccess(account));
        }
Example #2
0
        /// <summary>
        /// 登录用户验证
        /// </summary>
        /// <param name="account">账户</param>
        /// <param name="password">账户密码</param>
        /// <param name="ip">登录ip</param>
        /// <returns></returns>
        private async Task <Result <AccessToken> > Login(Account account, string password, string ip)
        {
            //判断用户是否禁止登陆和密码匹配
            if (!account.IsAllowLogin())
            {
                return(Result <AccessToken> .ReFailure(ResultCodes.AccountNotAllowedLogin));
            }
            if (!PasswordHelper.ValidatePassword(password, account.PasswordSalt, account.Password))
            {
                //获取是否有登录失败信息
                LoginFailed loginFailed = this.GetLoginFailedInfo(account.Username);
                loginFailed.Accumulative();
                if (loginFailed.FailedCount >= this.maxLoginFailedCount)
                {
                    return(Result <AccessToken> .ReFailure(ResultCodes.AccountPasswordNotSameOverrun));
                }
                return(Result <AccessToken> .ReFailure(ResultCodes.AccountPasswordNotSame2.ToFormat((this.maxLoginFailedCount - loginFailed.FailedCount).ToString())));
            }

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

            if (account.Department != null && account.Department.Role.Count > 0)
            {
                role.AddRange(account.Department.Role.Select(f => f.Name));
            }

            if (account.Role.Count > 0)
            {
                role.AddRange(account.Role.Select(f => f.Name));
            }
            var identity = new ClaimsIdentity(new GenericIdentity(HttpUtility.UrlEncode(account.Name), "AccessToken"));

            //去重复之后添加多角色
            identity.AddClaims(role.Distinct().Select(s => new Claim(ClaimTypes.Role, s)));
            // 添加账户信息
            identity.AddClaims(new[] {
                // new Claim(ClaimTypes.Role, role.Count > 0 ? string.Join(",",role.Distinct()) : "user"),
                new Claim("name", account.Username),
                // new Claim("nickname", HttpUtility.UrlEncode(account.Name)),
                new Claim("sub", account.Id.ToString()),
                new Claim("auth_mode", _loginType),
                new Claim("tenancy_id", ((long)account.TenancyId).ToString())
            });

            AccessToken accessToken = new AccessToken()
            {
                Token        = await GenerateTokenAsync(identity, 86400),
                RefreshToken = await GenerateTokenAsync(identity, 129600),
                Expired      = DateTime.Now.AddSeconds(86400)
            };

            // 判断是否存在已经拉黑的授权token
            if (!string.IsNullOrEmpty(account.Token))
            {
                await _serviceProvider.GetRequiredService <ISecurityTokenRepository>().Add(new SecurityToken()
                {
                    AccountId    = account.Id,
                    Token        = account.Token,
                    TokenExpired = account.Expired
                });
            }
            // 判断是否存在已经拉黑的刷新token
            if (!string.IsNullOrEmpty(account.RefreshToken))
            {
                await _serviceProvider.GetRequiredService <ISecurityTokenRepository>().Add(new SecurityToken()
                {
                    AccountId    = account.Id,
                    Token        = account.RefreshToken,
                    TokenExpired = account.Expired
                });
            }
            // 设置登录信息
            account.SetLoginInfo(accessToken, ip);
            // 登录日志
            LogInfo logInfo = new LogInfo()
            {
                Remark = "登录成功"
            };

            logInfo.SetLogin(account.Id, account.Username, _loginType, LoggingType.Login, account.LoginIp, account.LoginLocation);
            await _serviceProvider.GetRequiredService <LoggerService>().Create(logInfo);


            bool isUpdate = await _accountsRepository.Update(account);

            if (!isUpdate)
            {
                return(Result <AccessToken> .ReFailure(ResultCodes.AccountUpdateError));
            }
            //移除登录失败记录
            this.RemoveLoginFailedInfo(account.Username);
            return(Result <AccessToken> .ReSuccess(accessToken));
        }