using Domain.Exceptions;
using Features.Auth.Dtos;
using Features.Auth.Identity;
using Features.Auth.Services;
using MediatR;
using Microsoft.AspNetCore.Identity;
namespace Features.Auth.Commands.Authentication.ConfirmUser;
///
/// Handles by validating the confirmation token and marking the
/// corresponding user account as confirmed.
///
public class ConfirmUserHandler(
UserManager userManager,
IUserEmailStore emailStore,
ITokenService tokenService
) : IRequestHandler
{
///
/// Thrown when the confirmation token is invalid or expired, or when the associated user account cannot be found.
///
public async Task Handle(
ConfirmUserCommand request,
CancellationToken cancellationToken
)
{
ValidatedToken validatedToken = await tokenService.ValidateConfirmationTokenAsync(
request.Token
);
ApplicationUser? user = await userManager.FindByIdAsync(validatedToken.UserId.ToString());
if (user == null)
throw new UnauthorizedException("User account not found");
await emailStore.SetEmailConfirmedAsync(user, true, cancellationToken);
await userManager.UpdateAsync(user);
return new ConfirmationPayload(user.Id, DateTime.UtcNow);
}
}