mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-14 17:54:42 +00:00
79 lines
2.9 KiB
C#
79 lines
2.9 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Handles <see cref="RegisterUserCommand" />: creates the user via <see cref="UserManager{TUser}" />
|
|
/// (which validates uniqueness and hashes the password), issues access/refresh/confirmation tokens, and
|
|
/// publishes <see cref="UserRegisteredNotification" /> for Features.Emails to send the confirmation email.
|
|
/// </summary>
|
|
public class RegisterUserHandler(
|
|
UserManager<ApplicationUser> userManager,
|
|
ITokenService tokenService,
|
|
IMediator mediator
|
|
) : IRequestHandler<RegisterUserCommand, RegistrationPayload>
|
|
{
|
|
/// <exception cref="ConflictException">
|
|
/// Thrown when an existing account already has the same username or email address, or when user
|
|
/// creation otherwise fails.
|
|
/// </exception>
|
|
public async Task<RegistrationPayload> 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
|
|
);
|
|
}
|
|
}
|