CodeLiturgy.Dashboard/CodeLiturgy.Data.Auth/Users/Auth/AuthManager.cs

175 lines
6.7 KiB
C#
Raw Normal View History

2022-09-29 02:37:24 +03:00
using System;
2022-09-26 04:40:18 +03:00
using System.Security.Claims;
using BlueWest.Cryptography;
using BlueWest.Data.Application;
2022-09-27 20:12:13 +03:00
using BlueWest.Data.Application.Users;
2022-10-27 20:13:02 +03:00
using Microsoft.AspNetCore.Authentication.Cookies;
2022-09-26 04:40:18 +03:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
2022-09-27 20:12:13 +03:00
using static BlueWest.Data.Auth.Context.Users.AuthConsts;
2022-09-26 04:40:18 +03:00
2022-09-27 20:12:13 +03:00
namespace BlueWest.Data.Auth.Context.Users
2022-09-26 04:40:18 +03:00
{
2022-10-27 20:13:02 +03:00
/// <summary>
/// Authentication Manager for the Application Users
/// </summary>
2022-09-27 20:12:13 +03:00
public class AuthManager : IAuthManager
2022-09-26 04:40:18 +03:00
{
private readonly ApplicationUserManager _userManager;
private readonly IHasher _hasher;
private readonly IJwtFactory _jwtFactory;
private readonly ISessionCache _sessionCache;
/// <summary>
/// Auth manager constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="hasher"></param>
/// <param name="jwtFactory"></param>
/// <param name="sessionCache"></param>
public AuthManager(
ApplicationUserManager userManager,
IHasher hasher,
IJwtFactory jwtFactory,
ISessionCache sessionCache)
{
_userManager = userManager;
_hasher = hasher;
_jwtFactory = jwtFactory;
_sessionCache = sessionCache;
}
private async Task<SessionToken> GetSessionToken(LoginRequest loginRequest)
{
var uuid = loginRequest.GetUuid();
var hashUuid = GetHashFromUuid(uuid);
var sessionToken = await _sessionCache.GetSessionTokenByIdAsync(hashUuid);
return sessionToken;
}
private string GetHashFromUuid(string uuid)
{
return _hasher.CreateHash(uuid, BaseCryptoItem.HashAlgorithm.SHA2_512);
}
2022-10-27 20:13:02 +03:00
private SessionToken GetNewSessionToken(LoginRequest loginRequest, ApplicationUser user)
2022-09-26 04:40:18 +03:00
{
long timeNow = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var newToken = new SessionToken
{
Id = GetHashFromUuid(loginRequest.GetUuid()),
UserId = user.Id,
CreatedDate = timeNow,
IsValid = true,
2022-10-27 20:13:02 +03:00
ValidFor = SessionConstants.DefaultSessionMaxAge.Milliseconds
2022-09-26 04:40:18 +03:00
};
return newToken;
}
public bool SessionTokenIsValid(SessionToken token)
{
var hasChanges = token.Validate();
if (hasChanges)
{
_sessionCache.SaveAsync();
}
return token.IsValid;
}
2022-10-27 20:13:02 +03:00
public async Task<(bool, SessionTokenUnique, ClaimsIdentity)> GetSessionTokenIdByLoginRequest(LoginRequest loginRequest, string authenticationType = JwtBearerDefaults.AuthenticationScheme)
2022-09-26 04:40:18 +03:00
{
var user = await _userManager.FindByEmailAsync(loginRequest.Email);
if (user == null) return NegativeToken;
if (!await _userManager.CheckPasswordAsync(user, loginRequest.Password)) return NegativeToken;
2022-10-27 20:13:02 +03:00
var identity = new ClaimsIdentity(authenticationType);
2022-09-26 04:40:18 +03:00
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
2022-10-27 20:13:02 +03:00
identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
2022-09-26 04:40:18 +03:00
var sessionToken = await GetSessionToken(loginRequest);
if (sessionToken == null || !SessionTokenIsValid(sessionToken))
{
var (success, bearerToken) = await GenerateBearerToken(identity, user);
2022-10-27 20:13:02 +03:00
var newSessionToken = GetNewSessionToken(loginRequest, user);
2022-09-26 04:40:18 +03:00
await _sessionCache.AddSessionToken(newSessionToken);
var tokenUnique = new SessionTokenUnique(newSessionToken);
return OkAuth(tokenUnique, identity, success);
}
var response = new SessionTokenUnique(sessionToken);
return OkAuth(response, identity);
}
2022-10-27 20:13:02 +03:00
public async Task<(bool, SessionTokenUnique, ClaimsIdentity)> GetSessionTokenIdByLoginRequestViaCookie(LoginRequest loginRequest, string authenticationType = CookieAuthenticationDefaults.AuthenticationScheme)
{
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(authenticationType);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
var sessionToken = await GetSessionToken(loginRequest);
if (sessionToken == null || !SessionTokenIsValid(sessionToken))
{
var newSessionToken = GetNewSessionToken(loginRequest, user);
await _sessionCache.AddSessionToken(newSessionToken);
var tokenUnique = new SessionTokenUnique(newSessionToken);
return OkAuth(tokenUnique, identity);
}
var response = new SessionTokenUnique(sessionToken);
return OkAuth(response, identity);
}
2022-09-26 04:40:18 +03:00
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);
}
2022-10-27 20:13:02 +03:00
/// <summary>
/// Verify Password
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
2022-09-26 04:40:18 +03:00
public async Task<bool> VerifyLoginByEmailAsync(string email, string password)
{
var user = await _userManager.FindByEmailAsync(email);
return user != null && await _userManager.CheckPasswordAsync(user, password);
}
2022-10-27 20:13:02 +03:00
/// <summary>
/// Create user
/// </summary>
/// <param name="userSignupDto"></param>
/// <returns></returns>
public async Task<IdentityResult> CreateUserAsync(RegisterRequest userSignupDto)
2022-09-26 04:40:18 +03:00
{
userSignupDto.Password = _hasher.CreateHash(userSignupDto.Password, BaseCryptoItem.HashAlgorithm.SHA3_512);;
var newUser = userSignupDto.ToUser();
return await _userManager.CreateAsync(newUser);
}
}
}