53 lines
2.0 KiB
C#
53 lines
2.0 KiB
C#
using Heimdall.Application.Common;
|
|||
|
|
using Heimdall.Application.DTOs;
|
||
|
|
using Heimdall.Application.Services;
|
||
|
|
using Heimdall.Domain.Entities;
|
||
|
|
using MediatR;
|
||
|
|
using Microsoft.AspNetCore.Identity;
|
||
|
|
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 ILogger<Verify2faHandler> _logger;
|
||
|
|
|
||
|
|
public Verify2faHandler(
|
||
|
|
UserManager<AppUser> userManager,
|
||
|
|
IJwtService jwtService,
|
||
|
|
IRolePermissionService rolePermissionService,
|
||
|
|
ILogger<Verify2faHandler> logger)
|
||
|
|
{
|
||
|
|
_userManager = userManager;
|
||
|
|
_jwtService = jwtService;
|
||
|
|
_rolePermissionService = rolePermissionService;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<ServiceResult<AuthResponse>> Handle(Verify2faCommand request, CancellationToken ct)
|
||
|
|
{
|
||
|
|
_logger.LogDebug("Verify2fa: Email={Email}", request.Email);
|
||
|
|
|
||
|
|
var user = await _userManager.FindByEmailAsync(request.Email);
|
||
|
|
if (user is null)
|
||
|
|
{
|
||
|
|
_logger.LogWarning("Verify2fa: User not found Email={Email}", request.Email);
|
||
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid request");
|
||
|
|
}
|
||
|
|
|
||
|
|
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
|
||
|
|
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
|
||
|
|
|
||
|
|
if (!isValid)
|
||
|
|
{
|
||
|
|
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
|
||
|
|
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||
|
|
}
|
||
|
|
|
||
|
|
_logger.LogInformation("Verify2fa: Success Email={Email}", request.Email);
|
||
|
|
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||
|
|
}
|
||
|
|
}
|