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

86 lines
3.1 KiB
C#
Raw Normal View History

2022-09-10 00:33:17 +03:00
using System.Threading;
using System.Threading.Tasks;
using BlueWest.Cryptography;
using BlueWest.Data;
using Microsoft.AspNetCore.Identity;
namespace BlueWest.WebApi.Context.Users;
2022-09-11 01:22:04 +03:00
internal class AuthManager : IAuthManager
2022-09-10 00:33:17 +03:00
{
2022-09-10 07:12:03 +03:00
private readonly IUserManager _userManager;
private readonly UserRepository _usersRepo;
2022-09-10 00:33:17 +03:00
private readonly IHasher _hasher;
private readonly IJwtFactory _jwtFactory;
2022-09-10 07:12:03 +03:00
/// <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)
2022-09-10 00:33:17 +03:00
{
_userManager = userManager;
_hasher = hasher;
_usersRepo = usersRepo;
_jwtFactory = jwtFactory;
}
2022-09-10 07:12:03 +03:00
/// <inheritdoc />
2022-09-10 00:33:17 +03:00
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;
}
2022-09-10 07:12:03 +03:00
/// <inheritdoc />
2022-09-10 00:33:17 +03:00
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;
}
2022-09-10 07:12:03 +03:00
2022-09-10 00:33:17 +03:00
public async Task<IdentityResult> CreateUserAsync(RegisterViewModel userSignupDto)
{
2022-09-10 07:12:03 +03:00
RegisterViewModel userToCreate = FromSignupToUser(userSignupDto);
return await _userManager.CreateAsync(userToCreate.ToUser());
2022-09-10 00:33:17 +03:00
}
2022-09-10 07:12:03 +03:00
2022-09-10 00:33:17 +03:00
}