Files
Heimdall/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs
T

87 lines
4.0 KiB
C#
Raw Normal View History

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.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Verify2fa;
public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<AuthResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IApplicationDbContext _db;
private readonly ILogger<Verify2faHandler> _logger;
public Verify2faHandler(
UserManager<AppUser> userManager,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
IApplicationDbContext db,
ILogger<Verify2faHandler> logger)
{
_userManager = userManager;
_jwtService = jwtService;
_rolePermissionService = rolePermissionService;
_db = db;
_logger = logger;
}
public async Task<ServiceResult<AuthResponse>> Handle(Verify2faCommand request, CancellationToken ct)
{
var challenge = await LoginChallengeService.TakeAttemptAsync(_db, request.ChallengeId ?? "", ct);
if (challenge is null)
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired challenge");
var user = await _userManager.FindByIdAsync(challenge.UserId.ToString());
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)
|| await _userManager.IsLockedOutAsync(user)
|| (emailRequired && !user.EmailConfirmed))
return ServiceResult<AuthResponse>.Unauthorized("Account unavailable");
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
if (!isValid)
{
// TOTP invalide → tenter un code de récupération (usage unique)
var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
if (!redeemed)
{
_logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId);
await _userManager.AccessFailedAsync(user);
if (await _userManager.IsLockedOutAsync(user))
await _userManager.UpdateSecurityStampAsync(user);
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
}
if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1)
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
await _userManager.ResetAccessFailedCountAsync(user);
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser 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;
}
}