refactor: transfer two factor method to security

This commit is contained in:
Polianin Nikita 2024-11-02 01:09:15 +03:00
parent 3811d879ab
commit c5ba1cfcca
3 changed files with 27 additions and 6 deletions

View File

@ -0,0 +1,19 @@
using Mirea.Api.Dto.Common;
namespace Mirea.Api.Dto.Requests;
/// <summary>
/// Represents a request for verifying two-factor authentication.
/// </summary>
public class TwoFactorAuthRequest
{
/// <summary>
/// Gets or sets the two-factor authentication code provided by the user.
/// </summary>
public required string Code { get; set; }
/// <summary>
/// Gets or sets the type of the two-factor authentication method used (e.g., TOTP, Email).
/// </summary>
public TwoFactorAuthentication Method { get; set; }
}

View File

@ -54,11 +54,11 @@ public class AuthController(IOptionsSnapshot<Admin> user, AuthService auth, Pass
return Ok(tokenResult.ConvertToDto());
}
[HttpGet("Login")]
[HttpPost("2FA")]
[BadRequestResponse]
public async Task<ActionResult<TwoFactorAuthentication>> Login([FromQuery] string code)
public async Task<ActionResult<TwoFactorAuthentication>> TwoFactorAuth([FromBody] TwoFactorAuthRequest request)
{
var tokenResult = await auth.LoginAsync(GetCookieParams(), HttpContext, code);
var tokenResult = await auth.LoginAsync(GetCookieParams(), HttpContext, request.Method.ConvertFromDto(), request.Code);
return Ok(tokenResult ? TwoFactorAuthentication.None : TwoFactorAuthentication.TotpRequired);
}

View File

@ -93,12 +93,14 @@ public class AuthService(ICacheService cache, IAccessToken accessTokenService, I
authToken.Fingerprint);
}
public async Task<bool> LoginAsync(CookieOptionsParameters cookieOptions, HttpContext context, string code, CancellationToken cancellation = default)
public async Task<bool> LoginAsync(CookieOptionsParameters cookieOptions, HttpContext context, TwoFactorAuthenticator authenticator, string code, CancellationToken cancellation = default)
{
var requestContext = new RequestContextInfo(context, cookieOptions);
var firstTokenAuth = await cache.GetAsync<FirstAuthToken?>(GetFirstAuthCacheKey(requestContext.Fingerprint), cancellationToken: cancellation)
?? throw new SecurityException("The session time has expired");
var firstTokenAuth = await cache.GetAsync<FirstAuthToken?>(GetFirstAuthCacheKey(requestContext.Fingerprint), cancellationToken: cancellation);
if (firstTokenAuth == null || authenticator != firstTokenAuth.TwoFactorAuthenticator)
throw new SecurityException("The session time has expired");
switch (firstTokenAuth.TwoFactorAuthenticator)
{