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;
|
|
|
|
|
using Microsoft.AspNetCore.Identity;
|
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>>
|
|
|
|
|
{
|
|
|
|
|
private readonly UserManager<AppUser> _userManager;
|
|
|
|
|
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(
|
|
|
|
|
UserManager<AppUser> userManager,
|
|
|
|
|
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-10-20 07:21:28 +02:00
|
|
|
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");
|
2026-07-22 19:43:13 +00:00
|
|
|
|
|
|
|
|
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
|
|
|
|
|
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
|
|
|
|
|
|
|
|
|
|
if (!isValid)
|
|
|
|
|
{
|
2026-08-11 21:35:52 +02:00
|
|
|
// TOTP invalide → tenter un code de récupération (usage unique)
|
|
|
|
|
var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
|
|
|
|
|
if (!redeemed)
|
|
|
|
|
{
|
2026-10-20 07:21:28 +02:00
|
|
|
_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);
|
2026-08-11 21:35:52 +02:00
|
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
|
|
|
|
}
|
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");
|
|
|
|
|
await _userManager.ResetAccessFailedCountAsync(user);
|
|
|
|
|
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
|
2026-07-27 18:59:12 +00:00
|
|
|
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
}
|
2026-08-11 21:35:52 +02:00
|
|
|
|
|
|
|
|
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
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
|
|
|
}
|