public async Task <Result <TokenViewModel> > LogInAsync(LogInModel model) { User user; if (model.Email.IndexOf("@", StringComparison.Ordinal) > -1) { user = await _userRepository.GetUserByEmailAsync(model.Email); } else { user = await _userRepository.GetUserByPhoneAsync(model.Email); } if (user == null) { return(Result.Fail <TokenViewModel>(EC.UserNotFound, ET.UserNotFound)); } if (user.LockoutEnd.HasValue && user.LockoutEnd >= DateTimeOffset.UtcNow) { return(Result.Fail <TokenViewModel>(EC.AccessFailedCount, ET.AccessFailedCount)); } var verifyPassword = PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password); if (!verifyPassword) { await SetLockoutUser(user); return(Result.Fail <TokenViewModel>(EC.PasswordInvalid, ET.PasswordInvalid)); } var refreshToken = _jwtTokenHelper.GenerateRefreshToken(user); var logInViewModel = new TokenViewModel { RefreshToken = refreshToken, AccessToken = new AccessToken { Token = _jwtTokenHelper.GenerateToken(user), ExpiresIn = _globalSettings.Jwt.Expiration } }; user.RefreshToken = refreshToken; _userRepository.Put(user); await _unitOfWorks.CommitAsync(); return(Result.OK(logInViewModel)); }
public async Task <Result <TokenViewModel> > RefreshToken(TokenModel model) { // TODO check on null var principal = _jwtTokenHelper.GetPrincipalFromExpiredToken(model.AccessToken); var userId = principal.Claims.FirstOrDefault(x => x.Type == nameof(User.Id))?.Value; if (!int.TryParse(userId, out var result)) { return(Result.Fail <TokenViewModel>(EC.UserNotFound, ET.UserNotFound)); } var user = await _userRepository.GetUserByIdAsync(result); if (user == null || user.RefreshToken != model.RefreshToken) { return(Result.Fail <TokenViewModel>(EC.UserNotFound, ET.UserNotFound)); } var newJwtToken = _jwtTokenHelper.GenerateToken(user); var newRefreshToken = _jwtTokenHelper.GenerateRefreshToken(user); user.RefreshToken = newRefreshToken; _userRepository.Put(user); await _unitOfWorks.CommitAsync(); var tokenViewModel = new TokenViewModel { RefreshToken = newRefreshToken, AccessToken = new AccessToken { Token = newJwtToken, ExpiresIn = _globalSettings.Jwt.Expiration } }; return(Result.OK(tokenViewModel)); }