using System.Security.Claims; using BlueWest.Cryptography; using BlueWest.Data.Application.Users; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Identity; using static BlueWest.Data.Auth.Context.Users.AuthConsts; namespace BlueWest.Data.Auth.Context.Users { /// /// Authentication Manager for the Application Users /// public class AuthManager : IAuthManager { private readonly ApplicationUserManager _userManager; private readonly IHasher _hasher; private readonly IJwtFactory _jwtFactory; /// /// Auth manager constructor /// /// /// /// /// public AuthManager( ApplicationUserManager userManager, IHasher hasher, IJwtFactory jwtFactory) { _userManager = userManager; _hasher = hasher; _jwtFactory = jwtFactory; } private string GetHashFromUuid(string uuid) { return _hasher.CreateHash(uuid, BaseCryptoItem.HashAlgorithm.SHA2_512); } private async Task<(bool, string)> GenerateBearerToken(ClaimsIdentity identity, ApplicationUser user) { var jwtToken = await _jwtFactory.GenerateEncodedToken(user.Id, user.UserName); var completed = await _userManager.SetAuthenticationTokenAsync(user, SessionConstants.ApiNamePolicy, SessionConstants.ApiNamePolicy, jwtToken.Token); return (completed == IdentityResult.Success, jwtToken.Token); } /// /// Verify Password /// /// /// /// public async Task VerifyLoginByEmailAsync(string email, string password) { var user = await _userManager.FindByEmailAsync(email); return user != null && await _userManager.CheckPasswordAsync(user, password); } /// /// Create user /// /// /// public async Task CreateUserAsync(RegisterRequest userSignupDto) { userSignupDto.Password = _hasher.CreateHash(userSignupDto.Password, BaseCryptoItem.HashAlgorithm.SHA3_512);; var newUser = userSignupDto.ToUser(); return await _userManager.CreateAsync(newUser); } public async Task<(ClaimsIdentity, bool)> DoLogin(LoginRequest loginRequest) { var user = await _userManager.FindByEmailAsync(loginRequest.Email); if (user == null) return NegativeToken; if (!await _userManager.CheckPasswordAsync(user, loginRequest.Password)) return NegativeToken; var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); return (identity, true); } } }