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

155 lines
5.5 KiB
C#
Raw Normal View History

2022-09-17 22:13:35 +03:00
using System;
using System.Security.Claims;
2022-09-10 00:33:17 +03:00
using System.Threading.Tasks;
using BlueWest.Cryptography;
2022-09-17 22:13:35 +03:00
using BlueWest.Data.Application;
2022-09-18 04:00:24 +03:00
using Duende.IdentityServer.Extensions;
2022-09-17 22:13:35 +03:00
using Microsoft.AspNetCore.Authentication.Cookies;
2022-09-10 00:33:17 +03:00
using Microsoft.AspNetCore.Identity;
2022-09-18 04:00:24 +03:00
namespace BlueWest.WebApi.Context.Users
2022-09-10 00:33:17 +03:00
{
2022-09-18 04:00:24 +03:00
internal class AuthManager : IAuthManager
{
2022-09-17 22:13:35 +03:00
private readonly ApplicationUserManager _userManager;
2022-09-10 00:33:17 +03:00
private readonly IHasher _hasher;
private readonly IJwtFactory _jwtFactory;
2022-09-18 04:00:24 +03:00
private readonly ISessionCache _sessionCache;
2022-09-10 07:12:03 +03:00
/// <summary>
/// Auth manager constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="hasher"></param>
/// <param name="jwtFactory"></param>
2022-09-18 04:00:24 +03:00
/// <param name="sessionCache"></param>
2022-09-17 22:13:35 +03:00
public AuthManager(
2022-09-18 04:00:24 +03:00
ApplicationUserManager userManager,
IHasher hasher,
IJwtFactory jwtFactory,
ISessionCache sessionCache)
2022-09-10 00:33:17 +03:00
{
_userManager = userManager;
_hasher = hasher;
_jwtFactory = jwtFactory;
2022-09-18 04:00:24 +03:00
_sessionCache = sessionCache;
2022-09-17 22:13:35 +03:00
}
2022-09-18 04:00:24 +03:00
private async Task<SessionToken> GetSessionToken(LoginRequest loginRequest)
2022-09-17 22:13:35 +03:00
{
2022-09-18 04:00:24 +03:00
var uuid = loginRequest.GetUuid();
var hashUuid = GetHashFromUuid(uuid);
var sessionToken = await _sessionCache.GetSessionTokenByIdAsync(hashUuid);
if (sessionToken != null) return sessionToken;
return null;
}
2022-09-17 22:13:35 +03:00
2022-09-18 04:00:24 +03:00
private string GetHashFromUuid(string uuid)
{
return _hasher.CreateHash(uuid, BaseCryptoItem.HashAlgorithm.SHA2_512);
}
private SessionToken GetNewSessionToken(LoginRequest loginRequest, ApplicationUser user, string token)
{
long unixTime = ((DateTimeOffset)DateTimeOffset.Now).ToUnixTimeMilliseconds();;
var newToken = new SessionToken
2022-09-17 22:13:35 +03:00
{
2022-09-18 04:00:24 +03:00
Id = GetHashFromUuid(loginRequest.GetUuid()),
UserId = user.Id,
CreatedDate = unixTime,
IsValid = true,
AccessToken = token
};
return newToken;
}
public bool SessionTokenIsValid(SessionToken token)
{
var nowMilliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var isExpired = token.CreatedDate + token.ValidFor > nowMilliseconds;
if (isExpired)
{
token.IsValid = false;
_sessionCache.SaveAsync();
2022-09-17 22:13:35 +03:00
}
2022-09-18 04:00:24 +03:00
return token.IsValid;
2022-09-10 00:33:17 +03:00
}
2022-09-18 04:00:24 +03:00
public async Task<(bool, string, ClaimsIdentity)> GetSessionTokenId(LoginRequest loginRequest)
2022-09-10 00:33:17 +03:00
{
2022-09-18 04:00:24 +03:00
var user = await _userManager.FindByEmailAsync(loginRequest.Email);
if (user == null) return (false, string.Empty, null);
if (!await _userManager.CheckPasswordAsync(user, loginRequest.Password)) return (false, string.Empty, null);
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
// Session
var sessionToken = await GetSessionToken(loginRequest);
if (sessionToken != null)
2022-09-10 00:33:17 +03:00
{
2022-09-18 04:00:24 +03:00
if (SessionTokenIsValid(sessionToken))
2022-09-10 00:33:17 +03:00
{
2022-09-18 04:00:24 +03:00
return (true, sessionToken.Id, identity);
2022-09-10 00:33:17 +03:00
}
}
2022-09-18 04:00:24 +03:00
var (success, bearerToken) = await GenerateBearerToken(identity, user);
var newSessionToken = GetNewSessionToken(loginRequest, user, bearerToken);
await _sessionCache.AddSessionToken(newSessionToken);
return (success, newSessionToken.Id, identity);
2022-09-10 00:33:17 +03:00
}
2022-09-18 04:00:24 +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);
}
public async Task<(bool, string)> GetBearerTokenBySessionTokenId(string sessionId)
{
if (sessionId.IsNullOrEmpty()) return (false, string.Empty);
var bearer = await _sessionCache.GetBearerByAccessTokenId(sessionId);
return (bearer != string.Empty, bearer);
}
2022-09-10 07:12:03 +03:00
/// <inheritdoc />
2022-09-17 22:13:35 +03:00
public async Task<bool> VerifyLoginByEmailAsync(string email, string password)
2022-09-10 00:33:17 +03:00
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
2022-09-18 04:00:24 +03:00
return false;
2022-09-10 00:33:17 +03:00
}
return await _userManager.CheckPasswordAsync(user, password);
}
2022-09-18 04:00:24 +03:00
private RegisterViewModel FromSignupToUser(RegisterViewModel signupDto)
2022-09-10 00:33:17 +03:00
{
var pwd = signupDto.Password;
var hash = _hasher.CreateHash(pwd, BaseCryptoItem.HashAlgorithm.SHA3_512);
signupDto.Password = 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-18 04:00:24 +03:00
}
2022-09-10 00:33:17 +03:00
}