Migrate handlers to UserManager<>

This commit is contained in:
Aaron Po
2026-08-22 01:31:49 -04:00
parent 6b8e8d6208
commit ceadf125d8
9 changed files with 205 additions and 299 deletions

View File

@@ -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);
}
}