41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
using Heimdall.Application.Common;
|
|||
|
|
using Heimdall.Domain.Entities;
|
||
|
|
using MediatR;
|
||
|
|
using Microsoft.AspNetCore.Identity;
|
||
|
|
using Microsoft.Extensions.Logging;
|
||
|
|
|
||
|
|
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||
|
|
|
||
|
|
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult>
|
||
|
|
{
|
||
|
|
private readonly UserManager<AppUser> _userManager;
|
||
|
|
private readonly ILogger<Enable2faHandler> _logger;
|
||
|
|
|
||
|
|
public Enable2faHandler(UserManager<AppUser> userManager, ILogger<Enable2faHandler> logger)
|
||
|
|
{
|
||
|
|
_userManager = userManager;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult> Handle(Enable2faCommand request, CancellationToken ct)
|
||
|
|
{
|
||
|
|
_logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId);
|
||
|
|
|
||
|
|
var user = await _userManager.FindByIdAsync(request.UserId.ToString());
|
||
|
|
if (user is null)
|
||
|
|
{
|
||
|
|
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId);
|
||
|
|
return ServiceResult.NotFound("User not found");
|
||
|
|
}
|
||
|
|
|
||
|
|
var result = await _userManager.SetTwoFactorEnabledAsync(user, true);
|
||
|
|
if (!result.Succeeded)
|
||
|
|
{
|
||
|
|
_logger.LogError("Enable2fa: Failed UserId={UserId}", request.UserId);
|
||
|
|
return ServiceResult.Failure("Failed to enable 2FA");
|
||
|
|
}
|
||
|
|
|
||
|
|
_logger.LogInformation("Enable2fa: Enabled UserId={UserId}", request.UserId);
|
||
|
|
return ServiceResult.Success();
|
||
|
|
}
|
||
|
|
}
|