Files
Heimdall/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs
T

59 lines
2.9 KiB
C#
Raw Normal View History

using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Enable2fa;
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<Enable2faResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Enable2faHandler> _logger;
public Enable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
{
_userManager = userManager;
_db = db;
_logger = logger;
}
public async Task<ServiceResult<Enable2faResponse>> Handle(Enable2faCommand request, CancellationToken ct)
{
_logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId);
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId);
return ServiceResult<Enable2faResponse>.NotFound("User not found");
}
if (string.IsNullOrEmpty(request.CurrentPassword)
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.Failure("Current password is incorrect", 400);
if (await _userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.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).ConfigureAwait(false);
if (!reset.Succeeded)
return ServiceResult<Enable2faResponse>.Failure("Unable to initialize authenticator setup");
var key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
if (string.IsNullOrEmpty(key))
{
_logger.LogError("Enable2fa: Failed to generate authenticator key UserId={UserId}", request.UserId);
return ServiceResult<Enable2faResponse>.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<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
}
}