mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-15 10:04:44 +00:00
Migrate handlers to UserManager<>
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Repository;
|
||||
using Features.Auth.Identity;
|
||||
using Features.Auth.Services;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Features.Auth.Commands.ConfirmUser;
|
||||
|
||||
@@ -11,8 +11,11 @@ namespace Features.Auth.Commands.ConfirmUser;
|
||||
/// Handles <see cref="ConfirmUserCommand" /> by validating the confirmation token and marking the
|
||||
/// corresponding user account as confirmed.
|
||||
/// </summary>
|
||||
public class ConfirmUserHandler(IAuthRepository authRepository, ITokenService tokenService)
|
||||
: IRequestHandler<ConfirmUserCommand, ConfirmationPayload>
|
||||
public class ConfirmUserHandler(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IUserEmailStore<ApplicationUser> emailStore,
|
||||
ITokenService tokenService
|
||||
) : IRequestHandler<ConfirmUserCommand, ConfirmationPayload>
|
||||
{
|
||||
/// <exception cref="UnauthorizedException">
|
||||
/// Thrown when the confirmation token is invalid or expired, or when the associated user account cannot be found.
|
||||
@@ -26,11 +29,15 @@ public class ConfirmUserHandler(IAuthRepository authRepository, ITokenService to
|
||||
request.Token
|
||||
);
|
||||
|
||||
UserAccount? user = await authRepository.ConfirmUserAccountAsync(validatedToken.UserId);
|
||||
|
||||
ApplicationUser? user = await userManager.FindByIdAsync(
|
||||
validatedToken.UserId.ToString()
|
||||
);
|
||||
if (user == null)
|
||||
throw new UnauthorizedException("User account not found");
|
||||
|
||||
return new ConfirmationPayload(user.UserAccountId, DateTime.UtcNow);
|
||||
await emailStore.SetEmailConfirmedAsync(user, true, cancellationToken);
|
||||
await userManager.UpdateAsync(user);
|
||||
|
||||
return new ConfirmationPayload(user.Id, DateTime.UtcNow);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +1,35 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Repository;
|
||||
using Features.Auth.Identity;
|
||||
using Features.Auth.Services;
|
||||
using Infrastructure.PasswordHashing;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Features.Auth.Commands.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="LoginCommand" /> by verifying credentials and issuing access/refresh tokens.
|
||||
/// Handles <see cref="LoginCommand" /> by verifying credentials via
|
||||
/// <see cref="UserManager{TUser}" /> and issuing access/refresh tokens.
|
||||
/// </summary>
|
||||
public class LoginHandler(
|
||||
IAuthRepository authRepo,
|
||||
IPasswordInfrastructure passwordInfrastructure,
|
||||
ITokenService tokenService
|
||||
) : IRequestHandler<LoginCommand, LoginPayload>
|
||||
public class LoginHandler(UserManager<ApplicationUser> userManager, ITokenService tokenService)
|
||||
: IRequestHandler<LoginCommand, LoginPayload>
|
||||
{
|
||||
/// <exception cref="UnauthorizedException">
|
||||
/// Thrown when the username does not match any account, the account has no active credential,
|
||||
/// or the supplied password does not match the stored hash.
|
||||
/// Thrown when the username does not match any account or the supplied password does not match
|
||||
/// the stored hash.
|
||||
/// </exception>
|
||||
public async Task<LoginPayload> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
UserAccount user =
|
||||
await authRepo.GetUserByUsernameAsync(request.Username)
|
||||
ApplicationUser user =
|
||||
await userManager.FindByNameAsync(request.Username)
|
||||
?? throw new UnauthorizedException("Invalid username or password.");
|
||||
|
||||
// @todo handle expired passwords
|
||||
UserCredential activeCred =
|
||||
await authRepo.GetActiveCredentialByUserAccountIdAsync(user.UserAccountId)
|
||||
?? throw new UnauthorizedException("Invalid username or password.");
|
||||
|
||||
if (!passwordInfrastructure.Verify(request.Password, activeCred.Hash))
|
||||
if (!await userManager.CheckPasswordAsync(user, request.Password))
|
||||
throw new UnauthorizedException("Invalid username or password.");
|
||||
|
||||
string accessToken = tokenService.GenerateAccessToken(user.UserAccountId, user.Username);
|
||||
string refreshToken = tokenService.GenerateRefreshToken(user.UserAccountId, user.Username);
|
||||
string accessToken = tokenService.GenerateAccessToken(user.Id, user.UserName);
|
||||
string refreshToken = tokenService.GenerateRefreshToken(user.Id, user.UserName);
|
||||
|
||||
return new LoginPayload(user.UserAccountId, user.Username, refreshToken, accessToken);
|
||||
return new LoginPayload(user.Id, user.UserName, refreshToken, accessToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,84 +1,62 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Repository;
|
||||
using Features.Auth.Identity;
|
||||
using Features.Auth.Services;
|
||||
using Infrastructure.PasswordHashing;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Shared.Application.Emails;
|
||||
|
||||
namespace Features.Auth.Commands.RegisterUser;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="RegisterUserCommand" />: validates uniqueness, hashes the password, persists the
|
||||
/// account, issues access/refresh/confirmation tokens, and attempts to send the registration
|
||||
/// confirmation email via Features.Emails.
|
||||
/// 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
|
||||
/// attempts to send the registration confirmation email via Features.Emails.
|
||||
/// </summary>
|
||||
public class RegisterUserHandler(
|
||||
IAuthRepository authRepo,
|
||||
IPasswordInfrastructure passwordInfrastructure,
|
||||
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.
|
||||
/// 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
|
||||
)
|
||||
{
|
||||
await ValidateUserDoesNotExist(request.Username, request.Email);
|
||||
ApplicationUser user = new()
|
||||
{
|
||||
UserName = request.Username,
|
||||
Email = request.Email,
|
||||
FirstName = request.FirstName,
|
||||
LastName = request.LastName,
|
||||
DateOfBirth = request.DateOfBirth,
|
||||
};
|
||||
|
||||
string hashed = passwordInfrastructure.Hash(request.Password);
|
||||
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)));
|
||||
}
|
||||
|
||||
UserAccount createdUser = await authRepo.RegisterUserAsync(
|
||||
new UserAccount
|
||||
{
|
||||
Username = request.Username,
|
||||
FirstName = request.FirstName,
|
||||
LastName = request.LastName,
|
||||
DateOfBirth = request.DateOfBirth,
|
||||
Email = request.Email,
|
||||
UserCredential = new UserCredential
|
||||
{
|
||||
Hash = hashed,
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
string accessToken = tokenService.GenerateAccessToken(
|
||||
createdUser.UserAccountId,
|
||||
createdUser.Username
|
||||
);
|
||||
string refreshToken = tokenService.GenerateRefreshToken(
|
||||
createdUser.UserAccountId,
|
||||
createdUser.Username
|
||||
);
|
||||
string confirmationToken = tokenService.GenerateConfirmationToken(
|
||||
createdUser.UserAccountId,
|
||||
createdUser.Username
|
||||
);
|
||||
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(
|
||||
createdUser.UserAccountId,
|
||||
createdUser.Username,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
false
|
||||
);
|
||||
return new RegistrationPayload(user.Id, user.UserName, string.Empty, string.Empty, false);
|
||||
|
||||
bool emailSent = false;
|
||||
try
|
||||
{
|
||||
await mediator.Send(
|
||||
new SendRegistrationEmailCommand(
|
||||
createdUser.FirstName,
|
||||
createdUser.Email,
|
||||
confirmationToken
|
||||
),
|
||||
new SendRegistrationEmailCommand(user.FirstName, user.Email, confirmationToken),
|
||||
cancellationToken
|
||||
);
|
||||
emailSent = true;
|
||||
@@ -90,24 +68,6 @@ public class RegisterUserHandler(
|
||||
// ignored
|
||||
}
|
||||
|
||||
return new RegistrationPayload(
|
||||
createdUser.UserAccountId,
|
||||
createdUser.Username,
|
||||
refreshToken,
|
||||
accessToken,
|
||||
emailSent
|
||||
);
|
||||
}
|
||||
|
||||
/// <exception cref="ConflictException">
|
||||
/// Thrown when an existing account already has the same username or email address.
|
||||
/// </exception>
|
||||
private async Task ValidateUserDoesNotExist(string username, string email)
|
||||
{
|
||||
UserAccount? existingUsername = await authRepo.GetUserByUsernameAsync(username);
|
||||
UserAccount? existingEmail = await authRepo.GetUserByEmailAsync(email);
|
||||
|
||||
if (existingUsername != null || existingEmail != null)
|
||||
throw new ConflictException("Username or email already exists");
|
||||
return new RegistrationPayload(user.Id, user.UserName, refreshToken, accessToken, emailSent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using Domain.Entities;
|
||||
using Features.Auth.Repository;
|
||||
using Features.Auth.Identity;
|
||||
using Features.Auth.Services;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Shared.Application.Emails;
|
||||
|
||||
namespace Features.Auth.Commands.ResendConfirmationEmail;
|
||||
@@ -15,7 +15,7 @@ namespace Features.Auth.Commands.ResendConfirmationEmail;
|
||||
/// or if the user's account is already verified.
|
||||
/// </remarks>
|
||||
public class ResendConfirmationEmailHandler(
|
||||
IAuthRepository authRepository,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
ITokenService tokenService,
|
||||
IMediator mediator
|
||||
) : IRequestHandler<ResendConfirmationEmailCommand>
|
||||
@@ -25,17 +25,14 @@ public class ResendConfirmationEmailHandler(
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
UserAccount? user = await authRepository.GetUserByIdAsync(request.UserId);
|
||||
ApplicationUser? user = await userManager.FindByIdAsync(request.UserId.ToString());
|
||||
if (user == null)
|
||||
return; // Silent return to prevent user enumeration
|
||||
|
||||
if (await authRepository.IsUserVerifiedAsync(request.UserId))
|
||||
if (await userManager.IsEmailConfirmedAsync(user))
|
||||
return; // Already confirmed, no-op
|
||||
|
||||
string confirmationToken = tokenService.GenerateConfirmationToken(
|
||||
user.UserAccountId,
|
||||
user.Username
|
||||
);
|
||||
string confirmationToken = tokenService.GenerateConfirmationToken(user.Id, user.UserName);
|
||||
await mediator.Send(
|
||||
new SendResendConfirmationEmailCommand(user.FirstName, user.Email, confirmationToken),
|
||||
cancellationToken
|
||||
|
||||
Reference in New Issue
Block a user