using Domain.Entities;
using Domain.Exceptions;
using Features.Auth.Commands.Profile.CreateUserProfile;
using Features.Auth.Dtos;
using Features.Auth.Identity;
using Features.Auth.Notifications;
using Features.Auth.Services;
using MediatR;
using Microsoft.AspNetCore.Identity;
namespace Features.Auth.Commands.Authentication.RegisterUser;
///
/// Handles : creates the user via
/// (which validates uniqueness and hashes the password), issues access/refresh/confirmation tokens, and
/// publishes for Features.Emails to send the confirmation email.
///
public class RegisterUserHandler(
UserManager userManager,
ITokenService tokenService,
IMediator mediator
) : IRequestHandler
{
///
/// Thrown when an existing account already has the same username or email address, or when user
/// creation otherwise fails.
///
public async Task Handle(
RegisterUserCommand request,
CancellationToken cancellationToken
)
{
ApplicationUser user = new UserAccount
{
Username = request.Username,
Email = request.Email,
FirstName = request.FirstName,
LastName = request.LastName,
DateOfBirth = request.DateOfBirth,
}.ToApplicationUser();
IdentityResult result = await userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
{
if (result.Errors.Any(e => e.Code is "DuplicateUserName" or "DuplicateEmail"))
throw new ConflictException("Username or email already exists");
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
await mediator.Send(new CreateUserProfileCommand(user.Id, string.Empty), cancellationToken);
string accessToken = tokenService.GenerateAccessToken(user.Id, user.UserName);
string refreshToken = tokenService.GenerateRefreshToken(user.Id, user.UserName);
string confirmationToken = tokenService.GenerateConfirmationToken(user.Id, user.UserName);
if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(refreshToken))
return new RegistrationPayload(
user.Id,
user.UserName,
string.Empty,
string.Empty
);
await mediator.Publish(
new UserRegisteredNotification(user.Id, request.FirstName, user.Email, confirmationToken),
cancellationToken
);
return new RegistrationPayload(
user.Id,
user.UserName,
refreshToken,
accessToken
);
}
}