コード例 #1
0
        public async Task <LoginResponseData> Login(LoginRequestData model, string ip)
        {
            if (_dbPatchMgr.GetStatus())
            {
                throw new ApplicationException("Database syncronization in progress, please try to login in few minutes...");
            }
            _dbPatchMgr.Sync();

            var refreshTokenLifeTime = ValidateClientAuthentication(model.ClientId, model.ClientSecret);
            var user = await _userRepo.FindUserByUsername(model.Username);

            if (user == null)
            {
                throw new ApplicationException("Invalid username or password");
            }
            if (await _userRepo.IsUserLogout(user))
            {
                throw new ApplicationException("User account is been logout");
            }
            if (!user.IsActive)
            {
                throw new ApplicationException("User account inactive");
            }
            if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Failed)
            {
                throw new ApplicationException("Invalid username or password");
            }
            var jwtSecurityToken = TokenUtility.GenerateJwtSecurityToken(_appConfig.GetSection("AppConfiguration"), TokenUtility.GenerateClaims(user.UserName, user.Id));
            var userVm           = UserExtension.BuildUserViewModel(user);
            var refreshToken     = TokenUtility.GenerateRefreshToken();

            await SaveRefreshToken(model.ClientId, model.Username, refreshToken, refreshTokenLifeTime, ip);

            user.LastLoginDate = DateTime.UtcNow;
            _userRepo.Update(user);
            var response = new LoginResponseData()
            {
                UserId            = userVm.UserID,
                Username          = userVm.Username,
                FullName          = userVm.FullName,
                ProfilePictureUrl = userVm.ProfilePictureUrl,
                Roles             = userVm.Roles,
                Token             = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                TokenExpires      = jwtSecurityToken.ValidTo,
                TokenIssued       = jwtSecurityToken.ValidFrom,
                RefreshToken      = refreshToken,
                Email             = userVm.Email
            };

            return(response);
        }