using System.Threading; using System.Threading.Tasks; using BlueWest.Cryptography; using Microsoft.AspNetCore.Identity; namespace BlueWest.WebApi.Context.Users; internal class AuthManager : IAuthManager { private readonly IUserManager _userManager; private readonly UserRepository _usersRepo; private readonly IHasher _hasher; private readonly IJwtFactory _jwtFactory; /// /// Auth manager constructor /// /// /// /// /// public AuthManager(IUserManager userManager, IHasher hasher, UserRepository usersRepo, IJwtFactory jwtFactory) { _userManager = userManager; _hasher = hasher; _usersRepo = usersRepo; _jwtFactory = jwtFactory; } /// public async Task GetToken(LoginViewModel loginViewModel) { if (!string.IsNullOrEmpty(loginViewModel.Email) && !string.IsNullOrEmpty(loginViewModel.Password)) { var user = await _userManager.FindByEmailAsync(loginViewModel.Email); if (user != null) { if (await VerifyLoginAsync(loginViewModel.Email,loginViewModel.Password)) { // Todo generate refresh token // Todo Add refresh token await _usersRepo.UpdateAsync(user, CancellationToken.None); var token = await _jwtFactory.GenerateEncodedToken(user.Id.ToString(), user.UserName); // await _userManager.SetAuthenticationTokenAsync(user, "Income", "ApiUser", token.Token); return token; } } } return null; } /// public async Task VerifyLoginAsync(string email, string password) { var user = await _userManager.FindByEmailAsync(email); if (user == null) { return false; // return error user doesn't exist } return await _userManager.CheckPasswordAsync(user, password); // return await GenerateAuthenticationResultForUserAsync(user); } private RegisterViewModel FromSignupToUser(RegisterViewModel signupDto) { var pwd = signupDto.Password; var hash = _hasher.CreateHash(pwd, BaseCryptoItem.HashAlgorithm.SHA3_512); signupDto.Password = hash; signupDto.ConfirmPassword = hash; return signupDto; } public async Task CreateUserAsync(RegisterViewModel userSignupDto) { RegisterViewModel userToCreate = FromSignupToUser(userSignupDto); return await _userManager.CreateAsync(userToCreate.ToUser()); } }