formatting

This commit is contained in:
Aaron Po
2026-08-24 01:08:55 -04:00
parent c825d99b0a
commit b64c42ebde
27 changed files with 166 additions and 136 deletions

View File

@@ -103,7 +103,11 @@ public class RegisterUserHandlerTests
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), command.Password))
.ReturnsAsync(
IdentityResult.Failed(
new IdentityError { Code = "DuplicateUserName", Description = "Username taken." }
new IdentityError
{
Code = "DuplicateUserName",
Description = "Username taken.",
}
)
);

View File

@@ -14,7 +14,8 @@ public class ResendConfirmationEmailHandlerTests
private readonly ResendConfirmationEmailHandler _handler;
private readonly Mock<IMediator> _mediatorMock = new();
private readonly Mock<ITokenService> _tokenServiceMock = new();
private readonly Mock<UserManager<ApplicationUser>> _userManagerMock = UserManagerMockFactory.Create();
private readonly Mock<UserManager<ApplicationUser>> _userManagerMock =
UserManagerMockFactory.Create();
public ResendConfirmationEmailHandlerTests()
{

View File

@@ -87,7 +87,9 @@ public class LoginHandlerTests
ApplicationUser user = new() { Id = Guid.NewGuid(), UserName = username };
_userManagerMock.Setup(x => x.FindByNameAsync(username)).ReturnsAsync(user);
_userManagerMock.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>())).ReturnsAsync(false);
_userManagerMock
.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>()))
.ReturnsAsync(false);
Func<Task<LoginPayload>> act = async () =>
await _handler.Handle(new LoginCommand(username, "password"), CancellationToken.None);
@@ -104,7 +106,9 @@ public class LoginHandlerTests
ApplicationUser user = new() { Id = Guid.NewGuid(), UserName = username };
_userManagerMock.Setup(x => x.FindByNameAsync(username)).ReturnsAsync(user);
_userManagerMock.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>())).ReturnsAsync(false);
_userManagerMock
.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>()))
.ReturnsAsync(false);
Func<Task<LoginPayload>> act = async () =>
await _handler.Handle(

View File

@@ -29,9 +29,7 @@ public class ConfirmUserHandler(
request.Token
);
ApplicationUser? user = await userManager.FindByIdAsync(
validatedToken.UserId.ToString()
);
ApplicationUser? user = await userManager.FindByIdAsync(validatedToken.UserId.ToString());
if (user == null)
throw new UnauthorizedException("User account not found");

View File

@@ -27,7 +27,9 @@ public class DeleteAccountHandler(UserManager<ApplicationUser> userManager)
throw new ConflictException(
"Account cannot be deleted while it still has associated posts, comments, photos, or follows."
);
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
}
}

View File

@@ -18,7 +18,10 @@ public class LoginHandler(UserManager<ApplicationUser> userManager, ITokenServic
/// 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)
public async Task<LoginPayload> Handle(
LoginCommand request,
CancellationToken cancellationToken
)
{
ApplicationUser user =
await userManager.FindByNameAsync(request.Username)

View File

@@ -43,7 +43,9 @@ public class RegisterUserHandler(
{
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)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
string accessToken = tokenService.GenerateAccessToken(user.Id, user.UserName);
@@ -51,7 +53,13 @@ public class RegisterUserHandler(
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, false);
return new RegistrationPayload(
user.Id,
user.UserName,
string.Empty,
string.Empty,
false
);
bool emailSent = false;
try
@@ -68,6 +76,12 @@ public class RegisterUserHandler(
Console.WriteLine("Could not send email.");
}
return new RegistrationPayload(user.Id, user.UserName, refreshToken, accessToken, emailSent);
return new RegistrationPayload(
user.Id,
user.UserName,
refreshToken,
accessToken,
emailSent
);
}
}

View File

@@ -11,4 +11,5 @@ namespace Features.Auth.Commands.UpdateEmail;
/// The authenticated caller's own ID, extracted from the access token -- never bind this from
/// client-supplied input.
/// </param>
public record UpdateEmailCommand(Guid UserAccountId, string NewEmail) : IRequest<UpdateEmailPayload>;
public record UpdateEmailCommand(Guid UserAccountId, string NewEmail)
: IRequest<UpdateEmailPayload>;

View File

@@ -31,7 +31,9 @@ public class UpdateEmailHandler(UserManager<ApplicationUser> userManager)
{
if (result.Errors.Any(e => e.Code == "DuplicateEmail"))
throw new ConflictException("Email address already exists");
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
return new UpdateEmailPayload(user.Id, user.Email, user.EmailConfirmed);

View File

@@ -34,7 +34,9 @@ public class UpdatePasswordHandler(UserManager<ApplicationUser> userManager)
{
if (result.Errors.Any(e => e.Code == "PasswordMismatch"))
throw new UnauthorizedException("Current password is incorrect");
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
return new UpdatePasswordPayload(user.Id, DateTime.UtcNow);

View File

@@ -31,7 +31,9 @@ public class UpdateProfileHandler(UserManager<ApplicationUser> userManager)
IdentityResult result = await userManager.UpdateAsync(user);
if (!result.Succeeded)
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
return new UpdateProfilePayload(user.Id, user.FirstName, user.LastName, user.DateOfBirth);
}

View File

@@ -26,7 +26,9 @@ public class UpdateUsernameHandler(UserManager<ApplicationUser> userManager)
{
if (result.Errors.Any(e => e.Code == "DuplicateUserName"))
throw new ConflictException("Username already exists");
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
throw new ConflictException(
string.Join("; ", result.Errors.Select(e => e.Description))
);
}
return new UpdateUsernamePayload(user.Id, user.UserName);

View File

@@ -71,7 +71,9 @@ public class AuthController(IMediator mediator) : ControllerBase
/// </remarks>
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login([FromBody] LoginCommand command)
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login(
[FromBody] LoginCommand command
)
{
LoginPayload payload = await mediator.Send(command);
return Ok(

View File

@@ -22,6 +22,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Queries\" />
<Folder Include="Queries\" />
</ItemGroup>
</Project>

View File

@@ -19,8 +19,7 @@ public sealed class DapperUserStore(ISqlConnectionFactory connectionFactory)
IUserPasswordStore<ApplicationUser>,
IUserEmailStore<ApplicationUser>
{
private const string SelectUserSql =
"""
private const string SelectUserSql = """
SELECT UserAccountID AS Id, Username AS UserName, FirstName, LastName, Email, DateOfBirth
FROM dbo.UserAccount
""";
@@ -33,8 +32,10 @@ public sealed class DapperUserStore(ISqlConnectionFactory connectionFactory)
Task.FromResult(user.Id.ToString());
/// <inheritdoc />
public Task<string?> GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken) =>
Task.FromResult<string?>(user.UserName);
public Task<string?> GetUserNameAsync(
ApplicationUser user,
CancellationToken cancellationToken
) => Task.FromResult<string?>(user.UserName);
/// <inheritdoc />
public Task SetUserNameAsync(

View File

@@ -21,7 +21,12 @@ public enum TokenType
public record ValidatedToken(Guid UserId, string Username, ClaimsPrincipal Principal);
/// <summary>Represents the result of refreshing a user's session.</summary>
public record RefreshTokenResult(Guid UserId, string Username, string RefreshToken, string AccessToken);
public record RefreshTokenResult(
Guid UserId,
string Username,
string RefreshToken,
string AccessToken
);
/// <summary>
/// Defines the expiration windows, in hours, for each type of token issued by <see cref="ITokenService" />.
@@ -61,7 +66,6 @@ public interface ITokenService
/// </summary>
string GenerateConfirmationToken(Guid userId, string username);
/// <summary>Validates an access token's signature and expiration and extracts the caller's identity.</summary>
/// <exception cref="Domain.Exceptions.UnauthorizedException">
/// Thrown when the token is missing required claims, has a malformed user ID, or otherwise fails validation.

View File

@@ -23,9 +23,7 @@ public class CreateBreweryValidator : AbstractValidator<CreateBreweryCommand>
RuleFor(x => x.Location).NotNull().WithMessage("Location is required.");
RuleFor(x => x.Location.CityId)
.NotEmpty()
.WithMessage("CityId is required.");
RuleFor(x => x.Location.CityId).NotEmpty().WithMessage("CityId is required.");
RuleFor(x => x.Location.AddressLine1)
.NotEmpty()

View File

@@ -70,8 +70,7 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
}
/// <inheritdoc/>
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit,
int? offset)
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset)
{
await using DbConnection connection = await CreateConnection();
return await connection.QueryAsync<
@@ -122,25 +121,24 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
public async Task<BreweryPost> UpdateAsync(BreweryPost brewery)
{
await using DbConnection connection = await CreateConnection();
await using DbTransaction transaction =
await connection.BeginTransactionAsync();
await using DbTransaction transaction = await connection.BeginTransactionAsync();
try
{
bool breweryExists =
await connection.ExecuteScalarAsync<int?>(
new CommandDefinition(
"""
SELECT 1 FROM
dbo.BreweryPost
WHERE
BreweryPostID = @BreweryPostId
""",
new { brewery.BreweryPostId },
transaction
)
new CommandDefinition(
"""
SELECT 1 FROM
dbo.BreweryPost
WHERE
BreweryPostID = @BreweryPostId
""",
new { brewery.BreweryPostId },
transaction
)
is not null;
)
is not null;
if (!breweryExists)
throw new NotFoundException("Brewery not found.");
@@ -149,13 +147,13 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
{
bool cityExists =
await connection.ExecuteScalarAsync<int?>(
new CommandDefinition(
"SELECT 1 FROM dbo.City WHERE CityID = @CityId",
new { brewery.Location.CityId },
transaction
)
new CommandDefinition(
"SELECT 1 FROM dbo.City WHERE CityID = @CityId",
new { brewery.Location.CityId },
transaction
)
is not null;
)
is not null;
if (!cityExists)
throw new NotFoundException("City not found.");
@@ -207,17 +205,17 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
{
bool locationExists =
await connection.ExecuteScalarAsync<int?>(
new CommandDefinition(
"""
SELECT 1
FROM dbo.BreweryPostLocation
WHERE BreweryPostID = @BreweryPostId
""",
new { brewery.BreweryPostId },
transaction
)
new CommandDefinition(
"""
SELECT 1
FROM dbo.BreweryPostLocation
WHERE BreweryPostID = @BreweryPostId
""",
new { brewery.BreweryPostId },
transaction
)
is not null;
)
is not null;
if (locationExists)
await connection.ExecuteAsync(
@@ -288,9 +286,9 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
}
return await GetByIdAsync(brewery.BreweryPostId)
?? throw new InvalidOperationException(
$"Brewery '{brewery.BreweryPostId}' was not found after a successful update."
);
?? throw new InvalidOperationException(
$"Brewery '{brewery.BreweryPostId}' was not found after a successful update."
);
}
/// <inheritdoc/>
@@ -315,49 +313,47 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
public async Task CreateAsync(BreweryPost brewery)
{
if (brewery.Location is null)
throw new ArgumentException(
"Location must be provided when creating a brewery.");
throw new ArgumentException("Location must be provided when creating a brewery.");
await using DbConnection connection = await CreateConnection();
await using DbTransaction transaction =
await connection.BeginTransactionAsync();
await using DbTransaction transaction = await connection.BeginTransactionAsync();
try
{
bool userExists =
await connection.ExecuteScalarAsync<int?>(
new CommandDefinition(
"""
SELECT 1
FROM
dbo.UserAccount
WHERE
UserAccountID = @PostedById
""",
new { brewery.PostedById },
transaction
)
new CommandDefinition(
"""
SELECT 1
FROM
dbo.UserAccount
WHERE
UserAccountID = @PostedById
""",
new { brewery.PostedById },
transaction
)
is not null;
)
is not null;
if (!userExists)
throw new NotFoundException("User not found.");
bool cityExists =
await connection.ExecuteScalarAsync<int?>(
new CommandDefinition(
"""
SELECT 1
FROM
dbo.City
WHERE
CityID = @CityId
""",
new { brewery.Location.CityId },
transaction
)
new CommandDefinition(
"""
SELECT 1
FROM
dbo.City
WHERE
CityID = @CityId
""",
new { brewery.Location.CityId },
transaction
)
is not null;
)
is not null;
if (!cityExists)
throw new NotFoundException("City not found.");

View File

@@ -51,7 +51,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
WHERE CityName = @CityName AND StateProvinceID = @StateProvinceId
""",
new { location.CityName, StateProvinceId = stateProvinceId }
) is not null;
)
is not null;
if (!cityExists)
await connection.ExecuteAsync(
@@ -83,7 +84,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
WHERE ISO3166_1 = @ISO3166_1
""",
new { ISO3166_1 = isoCode }
) is not null;
)
is not null;
if (!exists)
// A concurrent caller may create this country between the check above and here; that
@@ -128,7 +130,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
WHERE ISO3166_2 = @ISO3166_2
""",
new { ISO3166_2 = isoCode }
) is not null;
)
is not null;
if (!exists)
await connection.ExecuteAsync(