using Heimdall.Application.Auth.Services; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Heimdall.Application.Auth.Commands.Verify2fa; public class Verify2faHandler : IRequestHandler> { private readonly IIdentityAccountService _userManager; private readonly IJwtService _jwtService; private readonly IRolePermissionService _rolePermissionService; private readonly IApplicationDbContext _db; private readonly ILogger _logger; public Verify2faHandler( IIdentityAccountService userManager, IJwtService jwtService, IRolePermissionService rolePermissionService, IApplicationDbContext db, ILogger logger) { _userManager = userManager; _jwtService = jwtService; _rolePermissionService = rolePermissionService; _db = db; _logger = logger; } public async Task> Handle(Verify2faCommand request, CancellationToken ct) { var challenge = await LoginChallengeService.TakeAttemptAsync(_db, request.ChallengeId ?? "", ct); if (challenge is null) return ServiceResult.Unauthorized("Invalid or expired challenge"); var user = await _userManager.FindByIdAsync(challenge.UserId, ct); 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 || !await _userManager.GetTwoFactorEnabledAsync(user, ct) || await _userManager.IsLockedOutAsync(user, ct) || (emailRequired && !user.EmailConfirmed)) return ServiceResult.Unauthorized("Account unavailable"); var isValid = await _userManager.VerifyAuthenticatorTokenAsync(user, request.Code, ct).ConfigureAwait(false); if (!isValid) { // TOTP invalide → tenter un code de récupération (usage unique) var recoveryCode = request.Code.Trim(); var redeemed = await TryRedeemRecoveryCodeAsync(user, recoveryCode, ct).ConfigureAwait(false); if (!redeemed) { // 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.Unauthorized("Invalid 2FA code"); } _logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId); await _userManager.AccessFailedAsync(user, ct); if (await _userManager.IsLockedOutAsync(user, ct)) await _userManager.UpdateSecurityStampAsync(user, ct); await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct); return ServiceResult.Unauthorized("Invalid 2FA code"); } 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.Failure("Unable to complete sign-in"); } _logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId); } if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1) return ServiceResult.Unauthorized("Challenge already used"); await _userManager.ResetAccessFailedCountAsync(user, ct); _logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId); return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false); } private async Task TryRedeemRecoveryCodeAsync(IdentityAccount user, string code, CancellationToken ct) { if (string.IsNullOrWhiteSpace(code)) return false; var codeHash = RecoveryCodeService.Hash(code); 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; } }