using Heimdall.Application.Auth.Services; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Heimdall.Application.Services; namespace Heimdall.Application.Auth.Commands.Enable2fa; public class Enable2faHandler : IRequestHandler> { private readonly IIdentityAccountService _userManager; private readonly IApplicationDbContext _db; private readonly ILogger _logger; public Enable2faHandler(IIdentityAccountService userManager, IApplicationDbContext db, ILogger logger) { _userManager = userManager; _db = db; _logger = logger; } public async Task> Handle(Enable2faCommand request, CancellationToken ct) { _logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId); var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false); if (user is null) { _logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId); return ServiceResult.NotFound("User not found"); } if (string.IsNullOrEmpty(request.CurrentPassword) || !await _userManager.CheckPasswordAsync(user, request.CurrentPassword, ct).ConfigureAwait(false)) return ServiceResult.Failure("Current password is incorrect", 400); if (await _userManager.GetTwoFactorEnabledAsync(user, ct).ConfigureAwait(false)) return ServiceResult.Conflict("Two-factor authentication is already enabled"); // Generate authenticator key for the QR code setup (l'utilisateur doit scanner le code avec son app) // Note: key is generated AFTER enabling 2FA so it's available immediately var reset = await _userManager.ResetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false); if (!reset.Succeeded) return ServiceResult.Failure("Unable to initialize authenticator setup"); var key = await _userManager.GetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false); if (string.IsNullOrEmpty(key)) { _logger.LogError("Enable2fa: Failed to generate authenticator key UserId={UserId}", request.UserId); return ServiceResult.Failure("Failed to generate 2FA key"); } var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30"; _logger.LogInformation("Authenticator setup initialized for user {UserId}; confirmation is still required", request.UserId); return ServiceResult.Success(new Enable2faResponse(key, qrCodeUri)); } }