CodeLiturgy.Dashboard/BlueWest.Api/Users/Auth/AuthManager.cs

85 lines
3.0 KiB
C#

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;
/// <summary>
/// Auth manager constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="hasher"></param>
/// <param name="usersRepo"></param>
/// <param name="jwtFactory"></param>
public AuthManager(IUserManager userManager, IHasher hasher, UserRepository usersRepo, IJwtFactory jwtFactory)
{
_userManager = userManager;
_hasher = hasher;
_usersRepo = usersRepo;
_jwtFactory = jwtFactory;
}
/// <inheritdoc />
public async Task<AccessToken> 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;
}
/// <inheritdoc />
public async Task<bool> 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<IdentityResult> CreateUserAsync(RegisterViewModel userSignupDto)
{
RegisterViewModel userToCreate = FromSignupToUser(userSignupDto);
return await _userManager.CreateAsync(userToCreate.ToUser());
}
}