2026-08-11 21:35:52 +02:00
|
|
|
using Heimdall.Application.Auth.Services;
|
2026-07-22 19:43:13 +00:00
|
|
|
using Heimdall.Application.Common;
|
|
|
|
|
using Heimdall.Application.DTOs;
|
|
|
|
|
using Heimdall.Application.Services;
|
|
|
|
|
using Heimdall.Domain.Entities;
|
|
|
|
|
using MediatR;
|
2026-08-11 21:35:52 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-22 19:43:13 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Application.Auth.Commands.Verify2fa;
|
|
|
|
|
|
|
|
|
|
public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<AuthResponse>>
|
|
|
|
|
{
|
2026-11-04 13:33:30 +01:00
|
|
|
private readonly IIdentityAccountService _userManager;
|
2026-07-22 19:43:13 +00:00
|
|
|
private readonly IJwtService _jwtService;
|
|
|
|
|
private readonly IRolePermissionService _rolePermissionService;
|
2026-08-11 21:35:52 +02:00
|
|
|
private readonly IApplicationDbContext _db;
|
2026-07-22 19:43:13 +00:00
|
|
|
private readonly ILogger<Verify2faHandler> _logger;
|
|
|
|
|
|
|
|
|
|
public Verify2faHandler(
|
2026-11-04 13:33:30 +01:00
|
|
|
IIdentityAccountService userManager,
|
2026-07-22 19:43:13 +00:00
|
|
|
IJwtService jwtService,
|
|
|
|
|
IRolePermissionService rolePermissionService,
|
2026-08-11 21:35:52 +02:00
|
|
|
IApplicationDbContext db,
|
2026-07-22 19:43:13 +00:00
|
|
|
ILogger<Verify2faHandler> logger)
|
|
|
|
|
{
|
|
|
|
|
_userManager = userManager;
|
|
|
|
|
_jwtService = jwtService;
|
|
|
|
|
_rolePermissionService = rolePermissionService;
|
2026-08-11 21:35:52 +02:00
|
|
|
_db = db;
|
2026-07-22 19:43:13 +00:00
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<ServiceResult<AuthResponse>> Handle(Verify2faCommand request, CancellationToken ct)
|
|
|
|
|
{
|
2026-10-20 07:21:28 +02:00
|
|
|
var challenge = await LoginChallengeService.TakeAttemptAsync(_db, request.ChallengeId ?? "", ct);
|
|
|
|
|
if (challenge is null)
|
|
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired challenge");
|
2026-07-22 19:43:13 +00:00
|
|
|
|
2026-11-04 13:33:30 +01:00
|
|
|
var user = await _userManager.FindByIdAsync(challenge.UserId, ct);
|
2026-10-20 07:21:28 +02:00
|
|
|
var emailSetting = await _db.AppSettings.AsNoTracking()
|
|
|
|
|
.Where(x => x.Key == "email.confirmation.required").Select(x => x.Value).SingleOrDefaultAsync(ct);
|
|
|
|
|
var emailRequired = string.Equals(emailSetting, "true", StringComparison.OrdinalIgnoreCase);
|
|
|
|
|
if (user is null || user.SecurityStamp != challenge.SecurityStamp
|
2026-11-04 13:33:30 +01:00
|
|
|
|| !await _userManager.GetTwoFactorEnabledAsync(user, ct)
|
|
|
|
|
|| await _userManager.IsLockedOutAsync(user, ct)
|
2026-10-20 07:21:28 +02:00
|
|
|
|| (emailRequired && !user.EmailConfirmed))
|
|
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Account unavailable");
|
2026-07-22 19:43:13 +00:00
|
|
|
|
2026-11-04 13:33:30 +01:00
|
|
|
var isValid = await _userManager.VerifyAuthenticatorTokenAsync(user, request.Code, ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
|
|
|
|
|
if (!isValid)
|
|
|
|
|
{
|
2026-08-11 21:35:52 +02:00
|
|
|
// TOTP invalide → tenter un code de récupération (usage unique)
|
2026-11-04 13:33:30 +01:00
|
|
|
var recoveryCode = request.Code.Trim();
|
|
|
|
|
var redeemed = await TryRedeemRecoveryCodeAsync(user, recoveryCode, ct).ConfigureAwait(false);
|
2026-08-11 21:35:52 +02:00
|
|
|
if (!redeemed)
|
|
|
|
|
{
|
2026-11-04 13:33:30 +01:00
|
|
|
// A parallel verifier may have atomically redeemed this exact code while
|
|
|
|
|
// this request waited on the database row lock. Do not race an access-failure
|
|
|
|
|
// update against the winner's security-stamp rotation.
|
|
|
|
|
var alreadyRedeemed = !string.IsNullOrWhiteSpace(recoveryCode)
|
|
|
|
|
&& await _db.UserRecoveryCodes.AnyAsync(r => r.UserId == user.Id
|
|
|
|
|
&& r.CodeHash == RecoveryCodeService.Hash(recoveryCode) && r.UsedAt != null, ct)
|
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
if (alreadyRedeemed)
|
|
|
|
|
{
|
|
|
|
|
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct).ConfigureAwait(false);
|
|
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-20 07:21:28 +02:00
|
|
|
_logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId);
|
2026-11-04 13:33:30 +01:00
|
|
|
await _userManager.AccessFailedAsync(user, ct);
|
|
|
|
|
if (await _userManager.IsLockedOutAsync(user, ct))
|
|
|
|
|
await _userManager.UpdateSecurityStampAsync(user, ct);
|
2026-10-20 07:21:28 +02:00
|
|
|
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
|
2026-08-11 21:35:52 +02:00
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
|
|
|
|
}
|
2026-11-04 13:33:30 +01:00
|
|
|
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
|
|
|
|
if (!stampUpdate)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
|
|
|
|
|
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
|
|
|
|
|
}
|
2026-10-20 07:21:28 +02:00
|
|
|
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
|
2026-07-22 19:43:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-10-20 07:21:28 +02:00
|
|
|
if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1)
|
|
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
|
2026-11-04 13:33:30 +01:00
|
|
|
await _userManager.ResetAccessFailedCountAsync(user, ct);
|
2026-10-20 07:21:28 +02:00
|
|
|
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
|
2026-11-04 13:33:30 +01:00
|
|
|
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
}
|
2026-08-11 21:35:52 +02:00
|
|
|
|
2026-11-04 13:33:30 +01:00
|
|
|
private async Task<bool> TryRedeemRecoveryCodeAsync(IdentityAccount user, string code, CancellationToken ct)
|
2026-08-11 21:35:52 +02:00
|
|
|
{
|
|
|
|
|
if (string.IsNullOrWhiteSpace(code))
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
var codeHash = RecoveryCodeService.Hash(code);
|
2026-10-20 07:21:28 +02:00
|
|
|
return await _db.UserRecoveryCodes
|
|
|
|
|
.Where(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null)
|
|
|
|
|
.ExecuteUpdateAsync(s => s.SetProperty(r => r.UsedAt, DateTime.UtcNow), ct) == 1;
|
2026-08-11 21:35:52 +02:00
|
|
|
}
|
2026-07-22 19:43:13 +00:00
|
|
|
}
|