mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-15 10:04:44 +00:00
Migrate Auth/Brewery/Location repositories to pure Dapper; rename Timer to RowVersion (#237)
* Integrate Spectre.Console into seed application, use async data loading * Replace stored-procedure repositories with Dapper-based repositories Removes the USP_* stored procedures for Auth, Location, and Brewery data access in favour of services built with Dapper. Adds a new Features.Locations slice and optimistic concurrency support for the Brewery slice. * Add new documentation for Dapper migration/database schema * Update FluentAssertions to most recent open source ver * Update XML doc comment in backend projects * Modify brewery location dto to include denormalized data * - Updated column names from 'Timer' to 'RowVersion' in schema.sql for - Introduced new BeerPost entity and updated BreweryPost and BreweryPostLocation entities to use 'RowVersion' for concurrency. - Modified UserAccount, UserCredential, UserVerification, City, StateProvince, and Country entities to use 'RowVersion' instead of 'Timer'. - Updated tests and command handlers to reflect changes in concurrency token from 'Timer' to 'RowVersion'. - Adjusted BreweryDto and BreweryDtoMapper to include 'RowVersion' and updated mapping logic accordingly. - Ensured all repository methods and interfaces are aligned with the new concurrency handling approach. * updates * Add BeerStyle entity and related properties; refactor BreweryDto to remove BeerPosts * Fix Api.Specs test failures: stale Timer column refs and missing test.user fixture * Remove repository tests, usages of registration dto used in repo * archive old stored procs/functions * update stale docs * Add instructions for generating cryptographically secure base64 secrets on macOS/Linux and Windows
This commit is contained in:
@@ -68,13 +68,13 @@ public class RegisterUserHandlerTests
|
||||
_authRepoMock
|
||||
.Setup(x =>
|
||||
x.RegisterUserAsync(
|
||||
new UserRegistrationDto(
|
||||
command.Username,
|
||||
command.FirstName,
|
||||
command.LastName,
|
||||
command.Email,
|
||||
command.DateOfBirth,
|
||||
hashedPassword
|
||||
It.Is<UserAccount>(ua =>
|
||||
ua.FirstName == command.FirstName
|
||||
&& ua.LastName == command.LastName
|
||||
&& ua.Username == command.Username
|
||||
&& ua.Email == command.Email
|
||||
&& ua.DateOfBirth == command.DateOfBirth
|
||||
&& ua.UserCredential!.Hash == hashedPassword
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -141,7 +141,7 @@ public class RegisterUserHandlerTests
|
||||
.WithMessage("Username or email already exists");
|
||||
|
||||
_authRepoMock.Verify(
|
||||
x => x.RegisterUserAsync(It.IsAny<UserRegistrationDto>()),
|
||||
x => x.RegisterUserAsync(It.IsAny<UserAccount>()),
|
||||
Times.Never
|
||||
);
|
||||
}
|
||||
@@ -186,7 +186,7 @@ public class RegisterUserHandlerTests
|
||||
_authRepoMock
|
||||
.Setup(x =>
|
||||
x.RegisterUserAsync(
|
||||
It.Is<UserRegistrationDto>(dto => dto.PasswordHash == hashedPassword)
|
||||
It.Is<UserAccount>(ua => ua.UserCredential!.Hash == hashedPassword)
|
||||
)
|
||||
)
|
||||
.ReturnsAsync(new UserAccount { UserAccountId = Guid.NewGuid() });
|
||||
@@ -204,13 +204,13 @@ public class RegisterUserHandlerTests
|
||||
_authRepoMock.Verify(
|
||||
x =>
|
||||
x.RegisterUserAsync(
|
||||
new UserRegistrationDto(
|
||||
command.Username,
|
||||
command.FirstName,
|
||||
command.LastName,
|
||||
command.Email,
|
||||
command.DateOfBirth,
|
||||
hashedPassword
|
||||
It.Is<UserAccount>(ua =>
|
||||
ua.FirstName == command.FirstName
|
||||
&& ua.LastName == command.LastName
|
||||
&& ua.Username == command.Username
|
||||
&& ua.DateOfBirth == command.DateOfBirth
|
||||
&& ua.Email == command.Email
|
||||
&& ua.UserCredential!.Hash == hashedPassword
|
||||
)
|
||||
),
|
||||
Times.Once
|
||||
@@ -230,7 +230,7 @@ public class RegisterUserHandlerTests
|
||||
.ReturnsAsync((UserAccount?)null);
|
||||
_passwordInfraMock.Setup(x => x.Hash(It.IsAny<string>())).Returns("hashed");
|
||||
_authRepoMock
|
||||
.Setup(x => x.RegisterUserAsync(It.IsAny<UserRegistrationDto>()))
|
||||
.Setup(x => x.RegisterUserAsync(It.IsAny<UserAccount>()))
|
||||
.ReturnsAsync(
|
||||
new UserAccount
|
||||
{
|
||||
|
||||
@@ -12,8 +12,7 @@
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.9.0" />
|
||||
<PackageReference Include="DbMocker" Version="1.26.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Auth.Commands.Login;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Queries.Login;
|
||||
using Features.Auth.Repository;
|
||||
using Features.Auth.Services;
|
||||
using FluentAssertions;
|
||||
@@ -68,7 +68,7 @@ public class LoginHandlerTests
|
||||
.Returns("refresh-token");
|
||||
|
||||
LoginPayload result = await _handler.Handle(
|
||||
new LoginQuery(username, "any-password"),
|
||||
new LoginCommand(username, "any-password"),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
@@ -88,7 +88,7 @@ public class LoginHandlerTests
|
||||
.ReturnsAsync((UserAccount?)null);
|
||||
|
||||
Func<Task<LoginPayload>> act = async () =>
|
||||
await _handler.Handle(new LoginQuery(username, "password"), CancellationToken.None);
|
||||
await _handler.Handle(new LoginCommand(username, "password"), CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<UnauthorizedException>();
|
||||
_authRepoMock.Verify(
|
||||
@@ -110,7 +110,7 @@ public class LoginHandlerTests
|
||||
.ReturnsAsync((UserCredential?)null);
|
||||
|
||||
Func<Task<LoginPayload>> act = async () =>
|
||||
await _handler.Handle(new LoginQuery(username, "password"), CancellationToken.None);
|
||||
await _handler.Handle(new LoginCommand(username, "password"), CancellationToken.None);
|
||||
|
||||
await act.Should()
|
||||
.ThrowAsync<UnauthorizedException>()
|
||||
@@ -144,7 +144,7 @@ public class LoginHandlerTests
|
||||
|
||||
Func<Task<LoginPayload>> act = async () =>
|
||||
await _handler.Handle(
|
||||
new LoginQuery(username, "wrong-password"),
|
||||
new LoginCommand(username, "wrong-password"),
|
||||
CancellationToken.None
|
||||
);
|
||||
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
using Apps72.Dev.Data.DbMocker;
|
||||
using Domain.Entities;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Repository;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace Features.Auth.Tests.Repository;
|
||||
|
||||
public class AuthRepositoryTests
|
||||
{
|
||||
private static AuthRepository CreateRepo(MockDbConnection conn)
|
||||
{
|
||||
return new AuthRepository(new TestConnectionFactory(conn));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterUserAsync_CreatesUserWithCredential_ReturnsUserAccount()
|
||||
{
|
||||
Guid expectedUserId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_RegisterUser").ReturnsScalar(expectedUserId);
|
||||
|
||||
// Mock the subsequent read for the newly created user by id
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountById")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
expectedUserId,
|
||||
"testuser",
|
||||
"Test",
|
||||
"User",
|
||||
"test@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
new DateTime(1990, 1, 1),
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserAccount result = await repo.RegisterUserAsync(
|
||||
new UserRegistrationDto(
|
||||
"testuser",
|
||||
"Test",
|
||||
"User",
|
||||
"test@example.com",
|
||||
new DateTime(1990, 1, 1),
|
||||
"hashedpassword123"
|
||||
)
|
||||
);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result.UserAccountId.Should().Be(expectedUserId);
|
||||
result.Username.Should().Be("testuser");
|
||||
result.FirstName.Should().Be("Test");
|
||||
result.LastName.Should().Be("User");
|
||||
result.Email.Should().Be("test@example.com");
|
||||
result.DateOfBirth.Should().Be(new DateTime(1990, 1, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserByEmailAsync_ReturnsUser_WhenExists()
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByEmail")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
userId,
|
||||
"emailuser",
|
||||
"Email",
|
||||
"User",
|
||||
"emailuser@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
new DateTime(1990, 5, 15),
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetUserByEmailAsync("emailuser@example.com");
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.UserAccountId.Should().Be(userId);
|
||||
result.Username.Should().Be("emailuser");
|
||||
result.Email.Should().Be("emailuser@example.com");
|
||||
result.FirstName.Should().Be("Email");
|
||||
result.LastName.Should().Be("User");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserByEmailAsync_ReturnsNull_WhenNotExists()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByEmail")
|
||||
.ReturnsTable(MockTable.Empty());
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetUserByEmailAsync("nonexistent@example.com");
|
||||
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserByUsernameAsync_ReturnsUser_WhenExists()
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByUsername")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
userId,
|
||||
"usernameuser",
|
||||
"Username",
|
||||
"User",
|
||||
"username@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
new DateTime(1985, 8, 20),
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetUserByUsernameAsync("usernameuser");
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.UserAccountId.Should().Be(userId);
|
||||
result.Username.Should().Be("usernameuser");
|
||||
result.Email.Should().Be("username@example.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserByUsernameAsync_ReturnsNull_WhenNotExists()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByUsername")
|
||||
.ReturnsTable(MockTable.Empty());
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetUserByUsernameAsync("nonexistent");
|
||||
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActiveCredentialByUserAccountIdAsync_ReturnsCredential_WhenExists()
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid credentialId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_GetActiveUserCredentialByUserAccountId")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserCredentialId", typeof(Guid)),
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Hash", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(credentialId, userId, "hashed_password_value", DateTime.UtcNow, null)
|
||||
);
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserCredential? result = await repo.GetActiveCredentialByUserAccountIdAsync(userId);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.UserCredentialId.Should().Be(credentialId);
|
||||
result.UserAccountId.Should().Be(userId);
|
||||
result.Hash.Should().Be("hashed_password_value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActiveCredentialByUserAccountIdAsync_ReturnsNull_WhenNotExists()
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_GetActiveUserCredentialByUserAccountId")
|
||||
.ReturnsTable(MockTable.Empty());
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
UserCredential? result = await repo.GetActiveCredentialByUserAccountIdAsync(userId);
|
||||
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RotateCredentialAsync_ExecutesSuccessfully()
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
string newPasswordHash = "new_hashed_password";
|
||||
MockDbConnection conn = new();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_RotateUserCredential").ReturnsScalar(1);
|
||||
|
||||
AuthRepository repo = CreateRepo(conn);
|
||||
|
||||
// Should not throw
|
||||
Func<Task> act = async () => await repo.RotateCredentialAsync(userId, newPasswordHash);
|
||||
await act.Should().NotThrowAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System.Data.Common;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.Auth.Tests.Repository;
|
||||
|
||||
internal class TestConnectionFactory(DbConnection conn) : ISqlConnectionFactory
|
||||
{
|
||||
private readonly DbConnection _conn = conn;
|
||||
|
||||
public DbConnection CreateConnection()
|
||||
{
|
||||
return _conn;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
using Features.Auth.Dtos;
|
||||
using MediatR;
|
||||
|
||||
namespace Features.Auth.Queries.Login;
|
||||
namespace Features.Auth.Commands.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates a user using their username and password and issues new tokens. Bound directly
|
||||
/// from the request body of <c>POST /api/auth/login</c>.
|
||||
/// </summary>
|
||||
public record LoginQuery(string Username, string Password) : IRequest<LoginPayload>;
|
||||
public record LoginCommand(string Username, string Password) : IRequest<LoginPayload>;
|
||||
@@ -6,22 +6,22 @@ using Features.Auth.Services;
|
||||
using Infrastructure.PasswordHashing;
|
||||
using MediatR;
|
||||
|
||||
namespace Features.Auth.Queries.Login;
|
||||
namespace Features.Auth.Commands.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="LoginQuery" /> by verifying credentials and issuing access/refresh tokens.
|
||||
/// Handles <see cref="LoginCommand" /> by verifying credentials and issuing access/refresh tokens.
|
||||
/// </summary>
|
||||
public class LoginHandler(
|
||||
IAuthRepository authRepo,
|
||||
IPasswordInfrastructure passwordInfrastructure,
|
||||
ITokenService tokenService
|
||||
) : IRequestHandler<LoginQuery, LoginPayload>
|
||||
) : 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.
|
||||
/// </exception>
|
||||
public async Task<LoginPayload> Handle(LoginQuery request, CancellationToken cancellationToken)
|
||||
public async Task<LoginPayload> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
UserAccount user =
|
||||
await authRepo.GetUserByUsernameAsync(request.Username)
|
||||
@@ -1,8 +1,9 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Features.Auth.Queries.Login;
|
||||
namespace Features.Auth.Commands.Login;
|
||||
|
||||
public class LoginValidator : AbstractValidator<LoginQuery>
|
||||
/// <summary>Validates that <see cref="LoginCommand.Username" /> and <see cref="LoginCommand.Password" /> are present.</summary>
|
||||
public class LoginValidator : AbstractValidator<LoginCommand>
|
||||
{
|
||||
public LoginValidator()
|
||||
{
|
||||
@@ -11,6 +11,10 @@ namespace Features.Auth.Commands.RefreshToken;
|
||||
public class RefreshTokenHandler(ITokenService tokenService)
|
||||
: IRequestHandler<RefreshTokenCommand, LoginPayload>
|
||||
{
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the refresh token is invalid or expired, or when the user account it refers to no
|
||||
/// longer exists.
|
||||
/// </exception>
|
||||
public async Task<LoginPayload> Handle(
|
||||
RefreshTokenCommand request,
|
||||
CancellationToken cancellationToken
|
||||
|
||||
@@ -2,6 +2,7 @@ using FluentValidation;
|
||||
|
||||
namespace Features.Auth.Commands.RefreshToken;
|
||||
|
||||
/// <summary>Validates that <see cref="RefreshTokenCommand.RefreshToken" /> is present.</summary>
|
||||
public class RefreshTokenValidator : AbstractValidator<RefreshTokenCommand>
|
||||
{
|
||||
public RefreshTokenValidator()
|
||||
|
||||
@@ -34,14 +34,18 @@ public class RegisterUserHandler(
|
||||
string hashed = passwordInfrastructure.Hash(request.Password);
|
||||
|
||||
UserAccount createdUser = await authRepo.RegisterUserAsync(
|
||||
new UserRegistrationDto(
|
||||
request.Username,
|
||||
request.FirstName,
|
||||
request.LastName,
|
||||
request.Email,
|
||||
request.DateOfBirth,
|
||||
hashed
|
||||
)
|
||||
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);
|
||||
|
||||
@@ -2,6 +2,10 @@ using FluentValidation;
|
||||
|
||||
namespace Features.Auth.Commands.RegisterUser;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the field-level constraints on <see cref="RegisterUserCommand" />: username format and
|
||||
/// length, name lengths, email format, minimum age of 19, and password complexity.
|
||||
/// </summary>
|
||||
public class RegisterUserValidator : AbstractValidator<RegisterUserCommand>
|
||||
{
|
||||
public RegisterUserValidator()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using Features.Auth.Commands.ConfirmUser;
|
||||
using Features.Auth.Commands.Login;
|
||||
using Features.Auth.Commands.RefreshToken;
|
||||
using Features.Auth.Commands.RegisterUser;
|
||||
using Features.Auth.Commands.ResendConfirmationEmail;
|
||||
using Features.Auth.Dtos;
|
||||
using Features.Auth.Queries.Login;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -23,6 +23,11 @@ namespace Features.Auth.Controllers;
|
||||
[Authorize(AuthenticationSchemes = "JWT")]
|
||||
public class AuthController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
/// <summary>Registers a new user account.</summary>
|
||||
/// <remarks>
|
||||
/// Anonymous access. Returns 201 Created with the new account's ID, username, and issued tokens.
|
||||
/// Returns 409 Conflict if the username or email is already taken.
|
||||
/// </remarks>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
public async Task<ActionResult<ResponseBody<RegistrationPayload>>> Register(
|
||||
@@ -40,11 +45,15 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Authenticates a user by username and password and issues a new access/refresh token pair.</summary>
|
||||
/// <remarks>
|
||||
/// Anonymous access. Returns 200 OK with the tokens, or 401 Unauthorized if the credentials are invalid.
|
||||
/// </remarks>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login([FromBody] LoginQuery query)
|
||||
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login([FromBody] LoginCommand command)
|
||||
{
|
||||
LoginPayload payload = await mediator.Send(query);
|
||||
LoginPayload payload = await mediator.Send(command);
|
||||
return Ok(
|
||||
new ResponseBody<LoginPayload>
|
||||
{
|
||||
@@ -54,6 +63,11 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Confirms a user account using a confirmation token.</summary>
|
||||
/// <remarks>
|
||||
/// Requires a valid JWT bearer token (no <c>[AllowAnonymous]</c> override). Returns 200 OK on success,
|
||||
/// or 401 Unauthorized if <paramref name="token" /> is invalid or expired.
|
||||
/// </remarks>
|
||||
[HttpPost("confirm")]
|
||||
public async Task<ActionResult<ResponseBody<ConfirmationPayload>>> Confirm(
|
||||
[FromQuery] string token
|
||||
@@ -69,6 +83,12 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Resends the account confirmation email for the given user, generating a fresh confirmation token.</summary>
|
||||
/// <remarks>
|
||||
/// Requires a valid JWT bearer token (no <c>[AllowAnonymous]</c> override). Always returns 200 OK, even
|
||||
/// if <paramref name="userId" /> does not exist or the account is already confirmed, to avoid user
|
||||
/// enumeration.
|
||||
/// </remarks>
|
||||
[HttpPost("confirm/resend")]
|
||||
public async Task<ActionResult<ResponseBody>> ResendConfirmation([FromQuery] Guid userId)
|
||||
{
|
||||
@@ -76,6 +96,11 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
return Ok(new ResponseBody { Message = "confirmation email has been resent" });
|
||||
}
|
||||
|
||||
/// <summary>Exchanges a valid refresh token for a new access/refresh token pair.</summary>
|
||||
/// <remarks>
|
||||
/// Anonymous access. Returns 200 OK with the new tokens, or 401 Unauthorized if the refresh token is
|
||||
/// invalid or expired.
|
||||
/// </remarks>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("refresh")]
|
||||
public async Task<ActionResult<ResponseBody<LoginPayload>>> Refresh(
|
||||
|
||||
@@ -5,8 +5,13 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Features.Auth.DependencyInjection;
|
||||
|
||||
/// <summary>Registers the services required by Features.Auth with the dependency injection container.</summary>
|
||||
public static class FeaturesAuthServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds <see cref="IAuthRepository" />, <see cref="ITokenService" />, and the Argon2 password hashing
|
||||
/// infrastructure as scoped services.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddFeaturesAuth(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IAuthRepository, AuthRepository>();
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace Features.Auth.Dtos;
|
||||
|
||||
public record UserRegistrationDto(
|
||||
string Username,
|
||||
string FirstName,
|
||||
string LastName,
|
||||
string Email,
|
||||
DateTime DateOfBirth,
|
||||
string PasswordHash
|
||||
);
|
||||
@@ -3,6 +3,7 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<RootNamespace>Features.Auth</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -19,4 +20,8 @@
|
||||
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Queries\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using Dapper;
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Auth.Dtos;
|
||||
using Infrastructure.Sql;
|
||||
using Microsoft.Data.SqlClient;
|
||||
@@ -8,155 +9,184 @@ using Microsoft.Data.SqlClient;
|
||||
namespace Features.Auth.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IAuthRepository" /> backed by SQL Server stored procedures,
|
||||
/// handling user registration, credential lookup/rotation, and account verification.
|
||||
/// Dapper-based implementation of <see cref="IAuthRepository" />, handling user registration,
|
||||
/// credential lookup/rotation, and account verification.
|
||||
/// </summary>
|
||||
public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<UserAccount>(connectionFactory),
|
||||
IAuthRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers a new user account and initial credential using the <c>USP_RegisterUser</c> stored
|
||||
/// procedure, then fetches and returns the newly created user.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The stored procedure's scalar result (expected to be the new user's ID) is parsed defensively:
|
||||
/// it may be returned as a <see cref="Guid" />, a parseable <see cref="string" />, or a 16-byte array.
|
||||
/// If the result cannot be interpreted, <see cref="Guid.Empty" /> is used, which will cause the
|
||||
/// subsequent lookup to fail.
|
||||
/// </remarks>
|
||||
/// <exception cref="Exception">Thrown when the newly registered user cannot be retrieved after registration.</exception>
|
||||
public async Task<UserAccount> RegisterUserAsync(UserRegistrationDto userRegistrationDto)
|
||||
/// <inheritdoc />
|
||||
/// <remarks>The account and credential are inserted within a single database transaction.</remarks>
|
||||
public async Task<UserAccount> RegisterUserAsync(UserAccount ua)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync();
|
||||
|
||||
command.CommandText = "USP_RegisterUser";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
var (username, firstName, lastName, email, dateOfBirth, passwordHash) = userRegistrationDto;
|
||||
Guid userAccountId;
|
||||
|
||||
AddParameter(command, "@Username", username);
|
||||
AddParameter(command, "@FirstName", firstName);
|
||||
AddParameter(command, "@LastName", lastName);
|
||||
AddParameter(command, "@Email", email);
|
||||
AddParameter(command, "@DateOfBirth", dateOfBirth);
|
||||
AddParameter(command, "@Hash", passwordHash);
|
||||
|
||||
object? result = await command.ExecuteScalarAsync();
|
||||
|
||||
Guid userAccountId = Guid.Empty;
|
||||
if (result != null && result != DBNull.Value)
|
||||
try
|
||||
{
|
||||
if (result is Guid g)
|
||||
userAccountId = g;
|
||||
else if (result is string s && Guid.TryParse(s, out Guid parsed))
|
||||
userAccountId = parsed;
|
||||
else if (result is byte[] bytes && bytes.Length == 16)
|
||||
userAccountId = new Guid(bytes);
|
||||
else
|
||||
// Fallback: try to convert and parse string representation
|
||||
try
|
||||
{
|
||||
string? str = result.ToString();
|
||||
if (!string.IsNullOrEmpty(str) && Guid.TryParse(str, out Guid p))
|
||||
userAccountId = p;
|
||||
}
|
||||
catch
|
||||
{
|
||||
userAccountId = Guid.Empty;
|
||||
}
|
||||
userAccountId = await connection.ExecuteScalarAsync<Guid>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.UserAccount (Username, FirstName, LastName, DateOfBirth, Email)
|
||||
OUTPUT INSERTED.UserAccountID
|
||||
VALUES (@Username, @FirstName, @LastName, @DateOfBirth, @Email);
|
||||
""",
|
||||
new { ua.Username, ua.FirstName, ua.LastName, ua.DateOfBirth, ua.Email},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
int credentialRows = await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.UserCredential (UserAccountId, Hash)
|
||||
VALUES (@UserAccountId, @Hash);
|
||||
""",
|
||||
new { UserAccountId = userAccountId, Hash = ua.UserCredential?.Hash },
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
if (credentialRows == 0)
|
||||
throw new InvalidOperationException("Failed to create user credential.");
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
|
||||
// perform round trip to get new User entity
|
||||
return await GetUserByIdAsync(userAccountId)
|
||||
?? throw new Exception("Failed to retrieve newly registered user.");
|
||||
}
|
||||
|
||||
/// <summary>Retrieves a user account by email using the <c>usp_GetUserAccountByEmail</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetUserByEmailAsync(string email)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountByEmail";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@Email", email);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE Email = @Email
|
||||
""",
|
||||
new { Email = email }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Retrieves a user account by username using the <c>usp_GetUserAccountByUsername</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetUserByUsernameAsync(string username)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountByUsername";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@Username", username);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE Username = @Username
|
||||
""",
|
||||
new { Username = username }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the active (non-revoked) credential for a user account using the
|
||||
/// <c>USP_GetActiveUserCredentialByUserAccountId</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserCredential?> GetActiveCredentialByUserAccountIdAsync(Guid userAccountId)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_GetActiveUserCredentialByUserAccountId";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@UserAccountId", userAccountId);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToCredentialEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserCredential>(
|
||||
"""
|
||||
SELECT UserCredentialId, UserAccountId, Hash, CreatedAt, RowVersion
|
||||
FROM dbo.UserCredential
|
||||
WHERE UserAccountId = @UserAccountId AND IsRevoked = 0
|
||||
""",
|
||||
new { UserAccountId = userAccountId }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rotates a user's credential by invalidating all existing credentials and creating a new one,
|
||||
/// using the <c>USP_RotateUserCredential</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public async Task RotateCredentialAsync(Guid userAccountId, string newPasswordHash)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_RotateUserCredential";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync();
|
||||
|
||||
AddParameter(command, "@UserAccountId_", userAccountId);
|
||||
AddParameter(command, "@Hash", newPasswordHash);
|
||||
try
|
||||
{
|
||||
bool exists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.UserAccount
|
||||
WHERE UserAccountID = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = userAccountId },
|
||||
transaction
|
||||
)
|
||||
) is not null;
|
||||
|
||||
await command.ExecuteNonQueryAsync();
|
||||
if (!exists)
|
||||
throw new NotFoundException("User account not found.");
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
UPDATE dbo.UserCredential
|
||||
SET IsRevoked = 1, RevokedAt = GETDATE()
|
||||
WHERE UserAccountId = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = userAccountId },
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.UserCredential (UserAccountId, Hash)
|
||||
VALUES (@UserAccountId, @Hash)
|
||||
""",
|
||||
new { UserAccountId = userAccountId, Hash = newPasswordHash },
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Retrieves a user account by ID using the <c>usp_GetUserAccountById</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetUserByIdAsync(Guid userAccountId)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountById";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@UserAccountId", userAccountId);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE UserAccountID = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = userAccountId }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a user account as confirmed by creating a verification record via the
|
||||
/// <c>USP_CreateUserVerification</c> stored procedure. If the user is already verified, this is a
|
||||
/// no-op and the existing user is returned (idempotent). If a concurrent request verifies the user
|
||||
/// first, the resulting duplicate-key SQL exception (error 2601/2627) is swallowed.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Confirmation is recorded by inserting a row into <c>dbo.UserVerification</c>. If a concurrent
|
||||
/// request verifies the same user first, the resulting duplicate-key SQL exception (error 2601/2627)
|
||||
/// is swallowed to keep the operation idempotent.
|
||||
/// </remarks>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">
|
||||
/// Thrown when the database command fails for a reason other than
|
||||
/// a duplicate verification record.
|
||||
/// Thrown when the database command fails for a reason other than a duplicate verification record.
|
||||
/// </exception>
|
||||
public async Task<UserAccount?> ConfirmUserAccountAsync(Guid userAccountId)
|
||||
{
|
||||
@@ -169,15 +199,16 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return user;
|
||||
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_CreateUserVerification";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@UserAccountID_", userAccountId);
|
||||
|
||||
try
|
||||
{
|
||||
await command.ExecuteNonQueryAsync();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO dbo.UserVerification (UserAccountId, VerificationDateTime)
|
||||
VALUES (@UserAccountId, GETDATE())
|
||||
""",
|
||||
new { UserAccountId = userAccountId }
|
||||
);
|
||||
}
|
||||
catch (SqlException ex) when (IsDuplicateVerificationViolation(ex))
|
||||
{
|
||||
@@ -188,19 +219,19 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await GetUserByIdAsync(userAccountId);
|
||||
}
|
||||
|
||||
/// <summary>Checks whether a user account has been verified by querying the <c>dbo.UserVerification</c> table.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> IsUserVerifiedAsync(Guid userAccountId)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText =
|
||||
"SELECT TOP 1 1 FROM dbo.UserVerification WHERE UserAccountID = @UserAccountID";
|
||||
command.CommandType = CommandType.Text;
|
||||
|
||||
AddParameter(command, "@UserAccountID", userAccountId);
|
||||
|
||||
object? result = await command.ExecuteScalarAsync();
|
||||
return result != null && result != DBNull.Value;
|
||||
int? result = await connection.ExecuteScalarAsync<int?>(
|
||||
"""
|
||||
SELECT TOP 1 1
|
||||
FROM dbo.UserVerification
|
||||
WHERE UserAccountID = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = userAccountId }
|
||||
);
|
||||
return result.HasValue;
|
||||
}
|
||||
|
||||
/// <summary>Determines whether a <see cref="SqlException" /> is a duplicate key violation (SQL Server error 2601 or 2627).</summary>
|
||||
@@ -209,67 +240,4 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
// 2601/2627 are duplicate key violations in SQL Server.
|
||||
return ex.Number == 2601 || ex.Number == 2627;
|
||||
}
|
||||
|
||||
protected override UserAccount MapToEntity(DbDataReader reader)
|
||||
{
|
||||
return new UserAccount
|
||||
{
|
||||
UserAccountId = reader.GetGuid(reader.GetOrdinal("UserAccountId")),
|
||||
Username = reader.GetString(reader.GetOrdinal("Username")),
|
||||
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
|
||||
LastName = reader.GetString(reader.GetOrdinal("LastName")),
|
||||
Email = reader.GetString(reader.GetOrdinal("Email")),
|
||||
CreatedAt = reader.GetDateTime(reader.GetOrdinal("CreatedAt")),
|
||||
UpdatedAt = reader.IsDBNull(reader.GetOrdinal("UpdatedAt"))
|
||||
? null
|
||||
: reader.GetDateTime(reader.GetOrdinal("UpdatedAt")),
|
||||
DateOfBirth = reader.GetDateTime(reader.GetOrdinal("DateOfBirth")),
|
||||
Timer = reader.IsDBNull(reader.GetOrdinal("Timer")) ? null : (byte[])reader["Timer"],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a data reader row to a UserCredential entity. The <c>Timer</c> column is mapped only if
|
||||
/// present in the reader's schema, allowing this method to support result sets that omit it.
|
||||
/// </summary>
|
||||
private static UserCredential MapToCredentialEntity(DbDataReader reader)
|
||||
{
|
||||
UserCredential entity = new()
|
||||
{
|
||||
UserCredentialId = reader.GetGuid(reader.GetOrdinal("UserCredentialId")),
|
||||
UserAccountId = reader.GetGuid(reader.GetOrdinal("UserAccountId")),
|
||||
Hash = reader.GetString(reader.GetOrdinal("Hash")),
|
||||
CreatedAt = reader.GetDateTime(reader.GetOrdinal("CreatedAt")),
|
||||
};
|
||||
|
||||
// Optional columns
|
||||
bool hasTimer =
|
||||
reader
|
||||
.GetSchemaTable()
|
||||
?.Rows.Cast<DataRow>()
|
||||
.Any(r =>
|
||||
string.Equals(
|
||||
r["ColumnName"]?.ToString(),
|
||||
"Timer",
|
||||
StringComparison.OrdinalIgnoreCase
|
||||
)
|
||||
)
|
||||
?? false;
|
||||
|
||||
if (hasTimer)
|
||||
entity.Timer = reader.IsDBNull(reader.GetOrdinal("Timer"))
|
||||
? null
|
||||
: (byte[])reader["Timer"];
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
/// <summary>Adds a parameter to a database command, converting <c>null</c> values to <see cref="DBNull.Value" />.</summary>
|
||||
private static void AddParameter(DbCommand command, string name, object? value)
|
||||
{
|
||||
DbParameter p = command.CreateParameter();
|
||||
p.ParameterName = name;
|
||||
p.Value = value ?? DBNull.Value;
|
||||
command.Parameters.Add(p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,21 +8,32 @@ namespace Features.Auth.Repository;
|
||||
/// </summary>
|
||||
public interface IAuthRepository
|
||||
{
|
||||
Task<UserAccount> RegisterUserAsync(UserRegistrationDto userRegistrationDto);
|
||||
/// <summary>
|
||||
/// Registers a new user account and its initial credential as a single atomic operation, then
|
||||
/// returns the created account.
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">Thrown when the newly registered user cannot be retrieved after registration.</exception>
|
||||
Task<UserAccount> RegisterUserAsync(UserAccount ua);
|
||||
|
||||
/// <summary>Retrieves a user account by email, or <see langword="null" /> if none exists.</summary>
|
||||
Task<UserAccount?> GetUserByEmailAsync(string email);
|
||||
|
||||
/// <summary>Retrieves a user account by username, or <see langword="null" /> if none exists.</summary>
|
||||
Task<UserAccount?> GetUserByUsernameAsync(string username);
|
||||
|
||||
/// <summary>Retrieves the active (non-revoked) credential for a user account, or <see langword="null" /> if none exists.</summary>
|
||||
Task<UserCredential?> GetActiveCredentialByUserAccountIdAsync(Guid userAccountId);
|
||||
|
||||
/// <summary>Rotates a user's credential by invalidating all existing credentials and creating a new one.</summary>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">Thrown when no account with <paramref name="userAccountId" /> exists.</exception>
|
||||
Task RotateCredentialAsync(Guid userAccountId, string newPasswordHash);
|
||||
|
||||
/// <summary>Marks a user account as confirmed. Idempotent if the account is already verified.</summary>
|
||||
Task<UserAccount?> ConfirmUserAccountAsync(Guid userAccountId);
|
||||
|
||||
/// <summary>Retrieves a user account by ID, or <see langword="null" /> if none exists.</summary>
|
||||
Task<UserAccount?> GetUserByIdAsync(Guid userAccountId);
|
||||
|
||||
/// <summary>Determines whether a user account has been verified.</summary>
|
||||
Task<bool> IsUserVerifiedAsync(Guid userAccountId);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ public record RefreshTokenResult(UserAccount UserAccount, string RefreshToken, s
|
||||
/// </summary>
|
||||
public static class TokenServiceExpirationHours
|
||||
{
|
||||
/// <summary>1 hour.</summary>
|
||||
public const double AccessTokenHours = 1;
|
||||
|
||||
/// <summary>21 days.</summary>
|
||||
@@ -43,10 +44,22 @@ public static class TokenServiceExpirationHours
|
||||
/// </summary>
|
||||
public interface ITokenService
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a signed access token for the given user, expiring after
|
||||
/// <see cref="TokenServiceExpirationHours.AccessTokenHours" /> hours.
|
||||
/// </summary>
|
||||
string GenerateAccessToken(UserAccount user);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a signed refresh token for the given user, expiring after
|
||||
/// <see cref="TokenServiceExpirationHours.RefreshTokenHours" /> hours.
|
||||
/// </summary>
|
||||
string GenerateRefreshToken(UserAccount user);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a signed confirmation token for the given user, expiring after
|
||||
/// <see cref="TokenServiceExpirationHours.ConfirmationTokenHours" /> hours.
|
||||
/// </summary>
|
||||
string GenerateConfirmationToken(UserAccount user);
|
||||
|
||||
/// <summary>Generates a token of the type specified by <typeparamref name="T" />.</summary>
|
||||
@@ -54,12 +67,28 @@ public interface ITokenService
|
||||
string GenerateToken<T>(UserAccount user)
|
||||
where T : struct, Enum;
|
||||
|
||||
/// <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.
|
||||
/// </exception>
|
||||
Task<ValidatedToken> ValidateAccessTokenAsync(string token);
|
||||
|
||||
/// <summary>Validates a refresh 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.
|
||||
/// </exception>
|
||||
Task<ValidatedToken> ValidateRefreshTokenAsync(string token);
|
||||
|
||||
/// <summary>Validates a confirmation 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.
|
||||
/// </exception>
|
||||
Task<ValidatedToken> ValidateConfirmationTokenAsync(string token);
|
||||
|
||||
/// <summary>Validates a refresh token and issues a new access/refresh token pair for the associated user.</summary>
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the refresh token is invalid or expired, or when the user account it refers to no
|
||||
/// longer exists.
|
||||
/// </exception>
|
||||
Task<RefreshTokenResult> RefreshTokenAsync(string refreshTokenString);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ public class TokenService : ITokenService
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GenerateAccessToken(UserAccount user)
|
||||
{
|
||||
DateTime expiresAt = DateTime.UtcNow.AddHours(TokenServiceExpirationHours.AccessTokenHours);
|
||||
@@ -59,6 +60,7 @@ public class TokenService : ITokenService
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GenerateRefreshToken(UserAccount user)
|
||||
{
|
||||
DateTime expiresAt = DateTime.UtcNow.AddHours(
|
||||
@@ -72,6 +74,7 @@ public class TokenService : ITokenService
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GenerateConfirmationToken(UserAccount user)
|
||||
{
|
||||
DateTime expiresAt = DateTime.UtcNow.AddHours(
|
||||
@@ -85,12 +88,7 @@ public class TokenService : ITokenService
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a token of the kind specified by <typeparamref name="T" />, dispatching to
|
||||
/// <see cref="GenerateAccessToken" />, <see cref="GenerateRefreshToken" />, or
|
||||
/// <see cref="GenerateConfirmationToken" />.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Must be <see cref="TokenType" />.</typeparam>
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Thrown when <typeparamref name="T" /> is not <see cref="TokenType" /> or does not resolve to a known token type.
|
||||
/// </exception>
|
||||
@@ -114,33 +112,25 @@ public class TokenService : ITokenService
|
||||
};
|
||||
}
|
||||
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the token is missing required claims, has a malformed user ID, or otherwise fails validation.
|
||||
/// </exception>
|
||||
/// <inheritdoc />
|
||||
public async Task<ValidatedToken> ValidateAccessTokenAsync(string token)
|
||||
{
|
||||
return await ValidateTokenInternalAsync(token, _accessTokenSecret, "access");
|
||||
}
|
||||
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the token is missing required claims, has a malformed user ID, or otherwise fails validation.
|
||||
/// </exception>
|
||||
/// <inheritdoc />
|
||||
public async Task<ValidatedToken> ValidateRefreshTokenAsync(string token)
|
||||
{
|
||||
return await ValidateTokenInternalAsync(token, _refreshTokenSecret, "refresh");
|
||||
}
|
||||
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the token is missing required claims, has a malformed user ID, or otherwise fails validation.
|
||||
/// </exception>
|
||||
/// <inheritdoc />
|
||||
public async Task<ValidatedToken> ValidateConfirmationTokenAsync(string token)
|
||||
{
|
||||
return await ValidateTokenInternalAsync(token, _confirmationTokenSecret, "confirmation");
|
||||
}
|
||||
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the refresh token is invalid, or when the user account it refers to no longer exists.
|
||||
/// </exception>
|
||||
/// <inheritdoc />
|
||||
public async Task<RefreshTokenResult> RefreshTokenAsync(string refreshTokenString)
|
||||
{
|
||||
ValidatedToken validated = await ValidateRefreshTokenAsync(refreshTokenString);
|
||||
|
||||
20
web/backend/Features/Features.Beers/Features.Beers.csproj
Normal file
20
web/backend/Features/Features.Beers/Features.Beers.csproj
Normal file
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Features.Breweries</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
|
||||
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
|
||||
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -21,6 +21,7 @@ public class UpdateBreweryHandlerTests
|
||||
{
|
||||
UpdateBreweryCommand command = new(
|
||||
Guid.NewGuid(),
|
||||
[0x01, 0x02],
|
||||
Guid.NewGuid(),
|
||||
"Renamed",
|
||||
"New description",
|
||||
@@ -31,7 +32,7 @@ public class UpdateBreweryHandlerTests
|
||||
_repoMock
|
||||
.Setup(r => r.UpdateAsync(It.IsAny<BreweryPost>()))
|
||||
.Callback<BreweryPost>(b => persisted = b)
|
||||
.Returns(Task.CompletedTask);
|
||||
.ReturnsAsync(() => persisted!);
|
||||
|
||||
DateTime before = DateTime.UtcNow;
|
||||
await _handler.Handle(command, CancellationToken.None);
|
||||
@@ -42,6 +43,7 @@ public class UpdateBreweryHandlerTests
|
||||
persisted.PostedById.Should().Be(command.PostedById);
|
||||
persisted.BreweryName.Should().Be("Renamed");
|
||||
persisted.Description.Should().Be("New description");
|
||||
persisted.RowVersion.Should().Equal(command.RowVersion);
|
||||
persisted.UpdatedAt.Should().NotBeNull();
|
||||
persisted.UpdatedAt!.Value.Should().BeOnOrAfter(before).And.BeOnOrBefore(after);
|
||||
}
|
||||
@@ -51,6 +53,7 @@ public class UpdateBreweryHandlerTests
|
||||
{
|
||||
UpdateBreweryCommand command = new(
|
||||
Guid.NewGuid(),
|
||||
[0x01, 0x02],
|
||||
Guid.NewGuid(),
|
||||
"Name",
|
||||
"Description",
|
||||
@@ -61,7 +64,7 @@ public class UpdateBreweryHandlerTests
|
||||
_repoMock
|
||||
.Setup(r => r.UpdateAsync(It.IsAny<BreweryPost>()))
|
||||
.Callback<BreweryPost>(b => persisted = b)
|
||||
.Returns(Task.CompletedTask);
|
||||
.ReturnsAsync(() => persisted!);
|
||||
|
||||
await _handler.Handle(command, CancellationToken.None);
|
||||
|
||||
@@ -81,6 +84,7 @@ public class UpdateBreweryHandlerTests
|
||||
);
|
||||
UpdateBreweryCommand command = new(
|
||||
Guid.NewGuid(),
|
||||
[0x01, 0x02],
|
||||
Guid.NewGuid(),
|
||||
"Name",
|
||||
"Description",
|
||||
@@ -91,7 +95,7 @@ public class UpdateBreweryHandlerTests
|
||||
_repoMock
|
||||
.Setup(r => r.UpdateAsync(It.IsAny<BreweryPost>()))
|
||||
.Callback<BreweryPost>(b => persisted = b)
|
||||
.Returns(Task.CompletedTask);
|
||||
.ReturnsAsync(() => persisted!);
|
||||
|
||||
await _handler.Handle(command, CancellationToken.None);
|
||||
|
||||
|
||||
@@ -12,8 +12,7 @@
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.9.0" />
|
||||
<PackageReference Include="DbMocker" Version="1.26.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
using Apps72.Dev.Data.DbMocker;
|
||||
using Domain.Entities;
|
||||
using Features.Breweries.Repository;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace Features.Breweries.Tests.Repository;
|
||||
|
||||
public class BreweryRepositoryTests
|
||||
{
|
||||
private static BreweryRepository CreateRepo(MockDbConnection conn)
|
||||
{
|
||||
return new BreweryRepository(new TestConnectionFactory(conn));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsBrewery_WhenExists()
|
||||
{
|
||||
Guid breweryId = Guid.NewGuid();
|
||||
MockDbConnection conn = new();
|
||||
|
||||
// Repository calls the stored procedure
|
||||
const string getByIdSql = "USP_GetBreweryById";
|
||||
|
||||
Guid locationId = Guid.NewGuid();
|
||||
|
||||
conn.Mocks.When(cmd => cmd.CommandText == getByIdSql)
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("BreweryPostId", typeof(Guid)),
|
||||
("PostedById", typeof(Guid)),
|
||||
("BreweryName", typeof(string)),
|
||||
("Description", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("Timer", typeof(byte[])),
|
||||
("BreweryPostLocationId", typeof(Guid)),
|
||||
("CityId", typeof(Guid)),
|
||||
("AddressLine1", typeof(string)),
|
||||
("AddressLine2", typeof(string)),
|
||||
("PostalCode", typeof(string)),
|
||||
("Coordinates", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
breweryId,
|
||||
Guid.NewGuid(),
|
||||
"Test Brewery",
|
||||
"A test brewery description",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
null,
|
||||
locationId,
|
||||
Guid.NewGuid(),
|
||||
"123 Main St",
|
||||
null,
|
||||
"12345",
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
BreweryRepository repo = CreateRepo(conn);
|
||||
BreweryPost? result = await repo.GetByIdAsync(breweryId);
|
||||
result.Should().NotBeNull();
|
||||
result!.BreweryPostId.Should().Be(breweryId);
|
||||
result.Location.Should().NotBeNull();
|
||||
result.Location!.BreweryPostLocationId.Should().Be(locationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsNull_WhenNotExists()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_GetBreweryById")
|
||||
.ReturnsTable(MockTable.Empty());
|
||||
BreweryRepository repo = CreateRepo(conn);
|
||||
BreweryPost? result = await repo.GetByIdAsync(Guid.NewGuid());
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ExecutesSuccessfully()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "USP_CreateBrewery").ReturnsScalar(1);
|
||||
BreweryRepository repo = CreateRepo(conn);
|
||||
BreweryPost brewery = new()
|
||||
{
|
||||
BreweryPostId = Guid.NewGuid(),
|
||||
PostedById = Guid.NewGuid(),
|
||||
BreweryName = "Test Brewery",
|
||||
Description = "A test brewery description",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Location = new BreweryPostLocation
|
||||
{
|
||||
BreweryPostLocationId = Guid.NewGuid(),
|
||||
CityId = Guid.NewGuid(),
|
||||
AddressLine1 = "123 Main St",
|
||||
PostalCode = "12345",
|
||||
Coordinates = [0x00, 0x01],
|
||||
},
|
||||
};
|
||||
|
||||
// Should not throw
|
||||
Func<Task> act = async () => await repo.CreateAsync(brewery);
|
||||
await act.Should().NotThrowAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System.Data.Common;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.Breweries.Tests.Repository;
|
||||
|
||||
internal class TestConnectionFactory(DbConnection conn) : ISqlConnectionFactory
|
||||
{
|
||||
private readonly DbConnection _conn = conn;
|
||||
|
||||
public DbConnection CreateConnection()
|
||||
{
|
||||
return _conn;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.CreateBrewery;
|
||||
|
||||
/// <summary>Location details for a brewery being created.</summary>
|
||||
/// <param name="Coordinates">Raw binary representation of the brewery's geographic coordinates.</param>
|
||||
public record CreateBreweryLocation(
|
||||
Guid CityId,
|
||||
string AddressLine1,
|
||||
|
||||
@@ -5,10 +5,14 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.CreateBrewery;
|
||||
|
||||
/// <summary>Handles <see cref="CreateBreweryCommand" /> by persisting a new brewery post.</summary>
|
||||
public class CreateBreweryHandler(IBreweryRepository repository)
|
||||
: IRequestHandler<CreateBreweryCommand, BreweryDto>
|
||||
{
|
||||
/// <summary>Creates a new brewery post, generating new identifiers for the post and its location.</summary>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">
|
||||
/// Thrown when <paramref name="request" />'s <c>PostedById</c> or <c>Location.CityId</c> does not exist.
|
||||
/// </exception>
|
||||
public async Task<BreweryDto> Handle(
|
||||
CreateBreweryCommand request,
|
||||
CancellationToken cancellationToken
|
||||
|
||||
@@ -2,6 +2,7 @@ using FluentValidation;
|
||||
|
||||
namespace Features.Breweries.Commands.CreateBrewery;
|
||||
|
||||
/// <summary>Validates <see cref="CreateBreweryCommand" />.</summary>
|
||||
public class CreateBreweryValidator : AbstractValidator<CreateBreweryCommand>
|
||||
{
|
||||
public CreateBreweryValidator()
|
||||
|
||||
@@ -2,4 +2,5 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.DeleteBrewery;
|
||||
|
||||
/// <summary>Deletes a brewery post. Bound directly from the route of <c>DELETE /api/brewery/{id}</c>.</summary>
|
||||
public record DeleteBreweryCommand(Guid BreweryPostId) : IRequest;
|
||||
|
||||
@@ -3,9 +3,13 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.DeleteBrewery;
|
||||
|
||||
/// <summary>Handles <see cref="DeleteBreweryCommand" /> by deleting the corresponding brewery post.</summary>
|
||||
public class DeleteBreweryHandler(IBreweryRepository repository)
|
||||
: IRequestHandler<DeleteBreweryCommand>
|
||||
{
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">
|
||||
/// Thrown when no brewery exists with <paramref name="request" />'s <c>BreweryPostId</c>.
|
||||
/// </exception>
|
||||
public Task Handle(DeleteBreweryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
return repository.DeleteAsync(request.BreweryPostId);
|
||||
|
||||
@@ -3,6 +3,11 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.UpdateBrewery;
|
||||
|
||||
/// <summary>Location details for a brewery being updated.</summary>
|
||||
/// <param name="BreweryPostLocationId">
|
||||
/// Identifier of the existing location row, if any; a new row is created if none exists yet.
|
||||
/// </param>
|
||||
/// <param name="Coordinates">Raw binary representation of the brewery's geographic coordinates.</param>
|
||||
public record UpdateBreweryLocation(
|
||||
Guid BreweryPostLocationId,
|
||||
Guid CityId,
|
||||
@@ -14,10 +19,13 @@ public record UpdateBreweryLocation(
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing brewery post. Bound directly from the request body of <c>PUT /api/brewery/{id}</c>.
|
||||
/// A <c>null</c> <see cref="Location" /> clears the brewery's location.
|
||||
/// A <c>null</c> <see cref="Location" /> clears the brewery's location. <see cref="RowVersion" /> must be the
|
||||
/// row-version last read for this brewery (e.g. from a prior <c>GET</c>); the update is rejected with a
|
||||
/// <c>409 Conflict</c> if the brewery was modified since then.
|
||||
/// </summary>
|
||||
public record UpdateBreweryCommand(
|
||||
Guid BreweryPostId,
|
||||
byte[] RowVersion,
|
||||
Guid PostedById,
|
||||
string BreweryName,
|
||||
string Description,
|
||||
|
||||
@@ -5,6 +5,7 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Commands.UpdateBrewery;
|
||||
|
||||
/// <summary>Handles <see cref="UpdateBreweryCommand" /> by persisting changes to an existing brewery post.</summary>
|
||||
public class UpdateBreweryHandler(IBreweryRepository repository)
|
||||
: IRequestHandler<UpdateBreweryCommand, BreweryDto>
|
||||
{
|
||||
@@ -12,6 +13,14 @@ public class UpdateBreweryHandler(IBreweryRepository repository)
|
||||
/// Updates an existing brewery post. If <paramref name="request" /> has no <c>Location</c>,
|
||||
/// the brewery's location is cleared.
|
||||
/// </summary>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">
|
||||
/// Thrown when no brewery exists with <paramref name="request" />'s <c>BreweryPostId</c>, or its
|
||||
/// location's <c>CityId</c> does not exist.
|
||||
/// </exception>
|
||||
/// <exception cref="Domain.Exceptions.ConflictException">
|
||||
/// Thrown when the brewery was modified by another request since <paramref name="request" />.
|
||||
/// <c>RowVersion</c> was read.
|
||||
/// </exception>
|
||||
public async Task<BreweryDto> Handle(
|
||||
UpdateBreweryCommand request,
|
||||
CancellationToken cancellationToken
|
||||
@@ -23,6 +32,7 @@ public class UpdateBreweryHandler(IBreweryRepository repository)
|
||||
PostedById = request.PostedById,
|
||||
BreweryName = request.BreweryName,
|
||||
Description = request.Description,
|
||||
RowVersion = request.RowVersion,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
Location = request.Location is null
|
||||
? null
|
||||
@@ -38,7 +48,7 @@ public class UpdateBreweryHandler(IBreweryRepository repository)
|
||||
},
|
||||
};
|
||||
|
||||
await repository.UpdateAsync(entity);
|
||||
return entity.ToDto();
|
||||
BreweryPost updated = await repository.UpdateAsync(entity);
|
||||
return updated.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Features.Breweries.Commands.UpdateBrewery;
|
||||
|
||||
/// <summary>Validates <see cref="UpdateBreweryCommand" />.</summary>
|
||||
public class UpdateBreweryValidator : AbstractValidator<UpdateBreweryCommand>
|
||||
{
|
||||
public UpdateBreweryValidator()
|
||||
{
|
||||
RuleFor(x => x.RowVersion)
|
||||
.NotEmpty()
|
||||
.WithMessage("RowVersion is required to detect conflicting concurrent updates.");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ using Shared.Contracts;
|
||||
|
||||
namespace Features.Breweries.Controllers;
|
||||
|
||||
/// <summary>Exposes CRUD operations for brewery posts.</summary>
|
||||
/// <remarks>
|
||||
/// Requires JWT authentication by default; <see cref="GetById" /> and <see cref="GetAll" /> opt out via
|
||||
/// <c>[AllowAnonymous]</c>.
|
||||
@@ -20,6 +21,7 @@ namespace Features.Breweries.Controllers;
|
||||
[Authorize(AuthenticationSchemes = "JWT")]
|
||||
public class BreweryController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
/// <summary>Retrieves a single brewery post by ID.</summary>
|
||||
/// <remarks>Allows anonymous access.</remarks>
|
||||
/// <returns><c>200 OK</c> with the brewery if found; otherwise <c>404 Not Found</c>.</returns>
|
||||
[AllowAnonymous]
|
||||
@@ -39,6 +41,9 @@ public class BreweryController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Retrieves brewery posts, newest first.</summary>
|
||||
/// <param name="limit">Maximum number of breweries to return. Unbounded if <see langword="null"/>.</param>
|
||||
/// <param name="offset">Number of breweries to skip. Treated as zero if <see langword="null"/>.</param>
|
||||
/// <remarks>Allows anonymous access.</remarks>
|
||||
[AllowAnonymous]
|
||||
[HttpGet]
|
||||
@@ -59,6 +64,7 @@ public class BreweryController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Creates a new brewery post.</summary>
|
||||
/// <returns><c>201 Created</c> with the newly created brewery.</returns>
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ResponseBody<BreweryDto>>> Create(
|
||||
@@ -76,8 +82,13 @@ public class BreweryController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Updates an existing brewery post.</summary>
|
||||
/// <param name="id">Must match <paramref name="command" />'s <c>BreweryPostId</c>.</param>
|
||||
/// <returns><c>200 OK</c> with the updated brewery; or <c>400 Bad Request</c> if the route ID does not match the payload ID.</returns>
|
||||
/// <returns>
|
||||
/// <c>200 OK</c> with the updated brewery; <c>400 Bad Request</c> if the route ID does not match the
|
||||
/// payload ID; <c>404 Not Found</c> if the brewery or its <c>CityId</c> does not exist; or
|
||||
/// <c>409 Conflict</c> if the brewery was modified since <c>command.RowVersion</c> was read.
|
||||
/// </returns>
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<ActionResult<ResponseBody<BreweryDto>>> Update(
|
||||
Guid id,
|
||||
@@ -97,7 +108,8 @@ public class BreweryController(IMediator mediator) : ControllerBase
|
||||
);
|
||||
}
|
||||
|
||||
/// <returns><c>200 OK</c> confirming the deletion.</returns>
|
||||
/// <summary>Deletes a brewery post.</summary>
|
||||
/// <returns><c>200 OK</c> confirming the deletion; <c>404 Not Found</c> if no brewery exists with <paramref name="id" />.</returns>
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<ActionResult<ResponseBody>> Delete(Guid id)
|
||||
{
|
||||
|
||||
@@ -3,11 +3,11 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Features.Breweries.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services owned by the Breweries feature slice.
|
||||
/// </summary>
|
||||
/// <summary>Registers the services required by the Breweries feature.</summary>
|
||||
public static class FeaturesBreweriesServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>Registers <see cref="IBreweryRepository" /> and its implementation.</summary>
|
||||
/// <returns><paramref name="services" />, for chaining.</returns>
|
||||
public static IServiceCollection AddFeaturesBreweries(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IBreweryRepository, BreweryRepository>();
|
||||
|
||||
@@ -1,39 +1,32 @@
|
||||
namespace Features.Breweries.Dtos;
|
||||
|
||||
public class BreweryLocationDto
|
||||
{
|
||||
public Guid BreweryPostLocationId { get; set; }
|
||||
/// <summary>Location details of a brewery, as returned by the API.</summary>
|
||||
/// <param name="Coordinates">The brewery's geographic coordinates, in a raw binary representation.</param>
|
||||
public record BreweryLocationDto(
|
||||
Guid BreweryPostLocationId,
|
||||
Guid CityId,
|
||||
string CityName,
|
||||
string StateProvinceName,
|
||||
string StateProvinceCode,
|
||||
string CountryName,
|
||||
string CountryCode,
|
||||
string AddressLine1,
|
||||
string? AddressLine2,
|
||||
string PostalCode,
|
||||
byte[]? Coordinates
|
||||
);
|
||||
|
||||
public Guid BreweryPostId { get; set; }
|
||||
|
||||
public Guid CityId { get; set; }
|
||||
|
||||
public string AddressLine1 { get; set; } = string.Empty;
|
||||
|
||||
public string? AddressLine2 { get; set; }
|
||||
|
||||
public string PostalCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Gets or sets the brewery's geographic coordinates, in a raw binary representation.</summary>
|
||||
public byte[]? Coordinates { get; set; }
|
||||
}
|
||||
|
||||
public class BreweryDto
|
||||
{
|
||||
public Guid BreweryPostId { get; set; }
|
||||
|
||||
public Guid PostedById { get; set; }
|
||||
|
||||
public string BreweryName { get; set; } = string.Empty;
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the row-version/concurrency token used to detect conflicting concurrent updates.</summary>
|
||||
public byte[]? Timer { get; set; }
|
||||
|
||||
public BreweryLocationDto? Location { get; set; }
|
||||
}
|
||||
/// <summary>A brewery post, as returned by the API.</summary>
|
||||
/// <param name="UpdatedAt">The date and time of the last edit, or <see langword="null"/> if never edited.</param>
|
||||
/// <param name="RowVersion">The row-version/concurrency token used to detect conflicting concurrent updates.</param>
|
||||
/// <param name="Location">The brewery's location, or <see langword="null"/> if none has been set.</param>
|
||||
public record BreweryDto(
|
||||
Guid BreweryPostId,
|
||||
Guid PostedById,
|
||||
string BreweryName,
|
||||
string Description,
|
||||
DateTime CreatedAt,
|
||||
DateTime? UpdatedAt,
|
||||
byte[]? RowVersion,
|
||||
BreweryLocationDto? Location
|
||||
);
|
||||
|
||||
@@ -2,31 +2,42 @@ using Domain.Entities;
|
||||
|
||||
namespace Features.Breweries.Dtos;
|
||||
|
||||
/// <summary>Maps <see cref="BreweryPost" /> domain entities to <see cref="BreweryDto" />.</summary>
|
||||
public static class BreweryDtoMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="BreweryPost" /> to its DTO representation, including its
|
||||
/// <see cref="BreweryDto.Location" /> if the entity has one.
|
||||
/// </summary>
|
||||
public static BreweryDto ToDto(this BreweryPost brewery)
|
||||
{
|
||||
return new BreweryDto
|
||||
{
|
||||
BreweryPostId = brewery.BreweryPostId,
|
||||
PostedById = brewery.PostedById,
|
||||
BreweryName = brewery.BreweryName,
|
||||
Description = brewery.Description,
|
||||
CreatedAt = brewery.CreatedAt,
|
||||
UpdatedAt = brewery.UpdatedAt,
|
||||
Timer = brewery.Timer,
|
||||
Location = brewery.Location is null
|
||||
return new BreweryDto(
|
||||
BreweryPostId: brewery.BreweryPostId,
|
||||
PostedById: brewery.PostedById,
|
||||
BreweryName: brewery.BreweryName,
|
||||
Description: brewery.Description,
|
||||
CreatedAt: brewery.CreatedAt,
|
||||
UpdatedAt: brewery.UpdatedAt,
|
||||
RowVersion: brewery.RowVersion,
|
||||
Location: brewery.Location is null
|
||||
? null
|
||||
: new BreweryLocationDto
|
||||
{
|
||||
BreweryPostLocationId = brewery.Location.BreweryPostLocationId,
|
||||
BreweryPostId = brewery.Location.BreweryPostId,
|
||||
CityId = brewery.Location.CityId,
|
||||
AddressLine1 = brewery.Location.AddressLine1,
|
||||
AddressLine2 = brewery.Location.AddressLine2,
|
||||
PostalCode = brewery.Location.PostalCode,
|
||||
Coordinates = brewery.Location.Coordinates,
|
||||
},
|
||||
};
|
||||
: new BreweryLocationDto(
|
||||
BreweryPostLocationId: brewery.Location.BreweryPostLocationId,
|
||||
CityId: brewery.Location.CityId,
|
||||
CityName: brewery.Location.City?.CityName ?? string.Empty,
|
||||
StateProvinceName: brewery.Location.City?.StateProvince?.StateProvinceName
|
||||
?? string.Empty,
|
||||
StateProvinceCode: brewery.Location.City?.StateProvince?.ISO3166_2
|
||||
?? string.Empty,
|
||||
CountryName: brewery.Location.City?.StateProvince?.Country?.CountryName
|
||||
?? string.Empty,
|
||||
CountryCode: brewery.Location.City?.StateProvince?.Country?.ISO3166_1
|
||||
?? string.Empty,
|
||||
AddressLine1: brewery.Location.AddressLine1,
|
||||
AddressLine2: brewery.Location.AddressLine2,
|
||||
PostalCode: brewery.Location.PostalCode,
|
||||
Coordinates: brewery.Location.Coordinates
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
|
||||
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
|
||||
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
|
||||
|
||||
@@ -5,9 +5,11 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Queries.GetAllBreweries;
|
||||
|
||||
/// <summary>Handles <see cref="GetAllBreweriesQuery" /> by retrieving brewery posts, newest first.</summary>
|
||||
public class GetAllBreweriesHandler(IBreweryRepository repository)
|
||||
: IRequestHandler<GetAllBreweriesQuery, IEnumerable<BreweryDto>>
|
||||
{
|
||||
/// <summary>Retrieves brewery posts, newest first, applying <see cref="GetAllBreweriesQuery" />'s paging.</summary>
|
||||
public async Task<IEnumerable<BreweryDto>> Handle(
|
||||
GetAllBreweriesQuery request,
|
||||
CancellationToken cancellationToken
|
||||
|
||||
@@ -3,7 +3,7 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Queries.GetAllBreweries;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a paginated list of brewery posts.
|
||||
/// </summary>
|
||||
/// <summary>Retrieves brewery posts, newest first. Bound directly from the query string of <c>GET /api/brewery</c>.</summary>
|
||||
/// <param name="Limit">Maximum number of breweries to return. Unbounded if <see langword="null"/>.</param>
|
||||
/// <param name="Offset">Number of breweries to skip. Treated as zero if <see langword="null"/>.</param>
|
||||
public record GetAllBreweriesQuery(int? Limit, int? Offset) : IRequest<IEnumerable<BreweryDto>>;
|
||||
|
||||
@@ -5,9 +5,11 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Queries.GetBreweryById;
|
||||
|
||||
/// <summary>Handles <see cref="GetBreweryByIdQuery" /> by retrieving the matching brewery post.</summary>
|
||||
public class GetBreweryByIdHandler(IBreweryRepository repository)
|
||||
: IRequestHandler<GetBreweryByIdQuery, BreweryDto?>
|
||||
{
|
||||
/// <summary>Retrieves the brewery post, or <see langword="null"/> if none exists with the given ID.</summary>
|
||||
public async Task<BreweryDto?> Handle(
|
||||
GetBreweryByIdQuery request,
|
||||
CancellationToken cancellationToken
|
||||
|
||||
@@ -3,4 +3,6 @@ using MediatR;
|
||||
|
||||
namespace Features.Breweries.Queries.GetBreweryById;
|
||||
|
||||
/// <summary>Retrieves a brewery post by ID. Bound directly from the route of <c>GET /api/brewery/{id}</c>.</summary>
|
||||
/// <remarks>Yields <see langword="null"/> if no brewery exists with the given <c>BreweryPostId</c>.</remarks>
|
||||
public record GetBreweryByIdQuery(Guid BreweryPostId) : IRequest<BreweryDto?>;
|
||||
|
||||
@@ -1,202 +1,458 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using Dapper;
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.Breweries.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IBreweryRepository" /> backed by SQL Server stored
|
||||
/// procedures.
|
||||
/// Dapper-based implementation of <see cref="IBreweryRepository" />.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <c>BreweryPostLocation.Coordinates</c> is a SQL Server <c>GEOGRAPHY</c> column. Dapper's generic
|
||||
/// <c>Query<T></c> deserializer reads columns via <c>IDataRecord.GetValue</c>, which for a UDT
|
||||
/// column returns a CLR UDT instance rather than raw bytes and cannot be coerced to <c>byte[]</c>.
|
||||
/// The read queries below therefore select <c>CONVERT(varbinary(max), bpl.Coordinates)</c>, which
|
||||
/// yields the UDT's serialized bytes as a plain <c>varbinary</c> value that Dapper can bind directly.
|
||||
/// </remarks>
|
||||
public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<BreweryPost>(connectionFactory),
|
||||
IBreweryRepository
|
||||
{
|
||||
/// <summary>Retrieves a brewery post by ID using the <c>USP_GetBreweryById</c> stored procedure.</summary>
|
||||
/// <inheritdoc/>
|
||||
public async Task<BreweryPost?> GetByIdAsync(Guid id)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
IEnumerable<BreweryPost> results = await connection.QueryAsync<
|
||||
BreweryPost,
|
||||
BreweryPostLocation,
|
||||
City,
|
||||
StateProvince,
|
||||
Country,
|
||||
BreweryPost
|
||||
>(
|
||||
"""
|
||||
SELECT
|
||||
bp.BreweryPostID,
|
||||
bp.PostedByID,
|
||||
bp.BreweryName,
|
||||
bp.Description,
|
||||
bp.CreatedAt,
|
||||
bp.UpdatedAt,
|
||||
bp.RowVersion,
|
||||
bpl.BreweryPostLocationID,
|
||||
bpl.AddressLine1,
|
||||
bpl.AddressLine2,
|
||||
bpl.PostalCode,
|
||||
CONVERT(varbinary(max), bpl.Coordinates) AS Coordinates,
|
||||
c.CityID,
|
||||
c.CityName,
|
||||
sp.StateProvinceID,
|
||||
sp.StateProvinceName,
|
||||
sp.ISO3166_2,
|
||||
co.CountryID,
|
||||
co.CountryName,
|
||||
co.ISO3166_1
|
||||
FROM dbo.BreweryPost bp
|
||||
LEFT JOIN dbo.BreweryPostLocation bpl ON bp.BreweryPostID = bpl.BreweryPostID
|
||||
LEFT JOIN dbo.City c ON bpl.CityID = c.CityID
|
||||
LEFT JOIN dbo.StateProvince sp ON c.StateProvinceID = sp.StateProvinceID
|
||||
LEFT JOIN dbo.Country co ON sp.CountryID = co.CountryID
|
||||
WHERE bp.BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
MapBreweryRow,
|
||||
new { BreweryPostId = id },
|
||||
splitOn: "BreweryPostLocationID,CityID,StateProvinceID,CountryID"
|
||||
);
|
||||
|
||||
command.CommandText = "USP_GetBreweryById";
|
||||
AddParameter(command, "@BreweryPostID", id);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
if (await reader.ReadAsync())
|
||||
return MapToEntity(reader);
|
||||
return null;
|
||||
return results.SingleOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all brewery posts, optionally paginated, using the <c>USP_GetAllBreweries</c>
|
||||
/// stored procedure. The <c>@Limit</c> and <c>@Offset</c> parameters are only added when their
|
||||
/// corresponding argument has a value.
|
||||
/// </summary>
|
||||
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset)
|
||||
/// <inheritdoc/>
|
||||
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit,
|
||||
int? offset)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_GetAllBreweries";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
if (limit.HasValue)
|
||||
AddParameter(command, "@Limit", limit.Value);
|
||||
|
||||
if (offset.HasValue)
|
||||
AddParameter(command, "@Offset", offset.Value);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
List<BreweryPost> breweries = new();
|
||||
|
||||
while (await reader.ReadAsync())
|
||||
breweries.Add(MapToEntity(reader));
|
||||
|
||||
return breweries;
|
||||
return await connection.QueryAsync<
|
||||
BreweryPost,
|
||||
BreweryPostLocation,
|
||||
City,
|
||||
StateProvince,
|
||||
Country,
|
||||
BreweryPost
|
||||
>(
|
||||
"""
|
||||
SELECT
|
||||
bp.BreweryPostID,
|
||||
bp.PostedByID,
|
||||
bp.BreweryName,
|
||||
bp.Description,
|
||||
bp.CreatedAt,
|
||||
bp.UpdatedAt,
|
||||
bp.RowVersion,
|
||||
bpl.BreweryPostLocationID,
|
||||
bpl.AddressLine1,
|
||||
bpl.AddressLine2,
|
||||
bpl.PostalCode,
|
||||
CONVERT(varbinary(max), bpl.Coordinates) AS Coordinates,
|
||||
c.CityID,
|
||||
c.CityName,
|
||||
sp.StateProvinceID,
|
||||
sp.StateProvinceName,
|
||||
sp.ISO3166_2,
|
||||
co.CountryID,
|
||||
co.CountryName,
|
||||
co.ISO3166_1
|
||||
FROM dbo.BreweryPost bp
|
||||
LEFT JOIN dbo.BreweryPostLocation bpl ON bp.BreweryPostID = bpl.BreweryPostID
|
||||
LEFT JOIN dbo.City c ON bpl.CityID = c.CityID
|
||||
LEFT JOIN dbo.StateProvince sp ON c.StateProvinceID = sp.StateProvinceID
|
||||
LEFT JOIN dbo.Country co ON sp.CountryID = co.CountryID
|
||||
ORDER BY bp.CreatedAt DESC
|
||||
OFFSET @Offset ROWS FETCH NEXT @Limit ROWS ONLY
|
||||
""",
|
||||
MapBreweryRow,
|
||||
new { Offset = offset ?? 0, Limit = limit ?? int.MaxValue },
|
||||
splitOn: "BreweryPostLocationID,CityID,StateProvinceID,CountryID"
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a brewery post's name and description, and upserts or clears its location, using the
|
||||
/// <c>USP_UpdateBrewery</c> stored procedure. When <paramref name="brewery" />.<c>Location</c> is
|
||||
/// <c>null</c>, any existing location for the brewery is removed.
|
||||
/// </summary>
|
||||
public async Task UpdateAsync(BreweryPost brewery)
|
||||
/// <inheritdoc/>
|
||||
public async Task<BreweryPost> UpdateAsync(BreweryPost brewery)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_UpdateBrewery";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
await using DbTransaction transaction =
|
||||
await connection.BeginTransactionAsync();
|
||||
|
||||
AddParameter(command, "@BreweryPostID", brewery.BreweryPostId);
|
||||
AddParameter(command, "@BreweryName", brewery.BreweryName);
|
||||
AddParameter(command, "@Description", brewery.Description);
|
||||
AddParameter(command, "@BreweryPostLocationID", brewery.Location?.BreweryPostLocationId);
|
||||
AddParameter(command, "@CityID", brewery.Location?.CityId);
|
||||
AddParameter(command, "@AddressLine1", brewery.Location?.AddressLine1);
|
||||
AddParameter(command, "@AddressLine2", brewery.Location?.AddressLine2);
|
||||
AddParameter(command, "@PostalCode", brewery.Location?.PostalCode);
|
||||
AddParameter(command, "@Coordinates", brewery.Location?.Coordinates);
|
||||
try
|
||||
{
|
||||
bool breweryExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1 FROM
|
||||
dbo.BreweryPost
|
||||
WHERE
|
||||
BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
)
|
||||
is not null;
|
||||
|
||||
await command.ExecuteNonQueryAsync();
|
||||
if (!breweryExists)
|
||||
throw new NotFoundException("Brewery not found.");
|
||||
|
||||
if (brewery.Location is not null)
|
||||
{
|
||||
bool cityExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"SELECT 1 FROM dbo.City WHERE CityID = @CityId",
|
||||
new { brewery.Location.CityId },
|
||||
transaction
|
||||
)
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!cityExists)
|
||||
throw new NotFoundException("City not found.");
|
||||
}
|
||||
|
||||
int updatedRows = await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
UPDATE dbo.BreweryPost
|
||||
SET BreweryName = @BreweryName,
|
||||
Description = @Description,
|
||||
UpdatedAt = GETDATE()
|
||||
WHERE
|
||||
BreweryPostID = @BreweryPostId
|
||||
AND RowVersion = @RowVersion
|
||||
""",
|
||||
new
|
||||
{
|
||||
brewery.BreweryPostId,
|
||||
brewery.BreweryName,
|
||||
brewery.Description,
|
||||
brewery.RowVersion,
|
||||
},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
if (updatedRows == 0)
|
||||
throw new ConflictException(
|
||||
"Brewery was modified by another request. Reload and try again."
|
||||
);
|
||||
|
||||
if (brewery.Location is null)
|
||||
{
|
||||
// No location supplied: clear any existing location for this brewery.
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
DELETE FROM
|
||||
dbo.BreweryPostLocation
|
||||
WHERE BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
bool locationExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.BreweryPostLocation
|
||||
WHERE BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (locationExists)
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
UPDATE dbo.BreweryPostLocation
|
||||
SET CityID = @CityId,
|
||||
AddressLine1 = @AddressLine1,
|
||||
AddressLine2 = @AddressLine2,
|
||||
PostalCode = @PostalCode,
|
||||
Coordinates = @Coordinates
|
||||
WHERE BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new
|
||||
{
|
||||
brewery.BreweryPostId,
|
||||
brewery.Location.CityId,
|
||||
brewery.Location.AddressLine1,
|
||||
brewery.Location.AddressLine2,
|
||||
brewery.Location.PostalCode,
|
||||
brewery.Location.Coordinates,
|
||||
},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
else
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.BreweryPostLocation
|
||||
(BreweryPostLocationID,
|
||||
BreweryPostID,
|
||||
CityID,
|
||||
AddressLine1,
|
||||
AddressLine2,
|
||||
PostalCode,
|
||||
Coordinates)
|
||||
VALUES
|
||||
(@BreweryPostLocationId,
|
||||
@BreweryPostId,
|
||||
@CityId,
|
||||
@AddressLine1,
|
||||
@AddressLine2,
|
||||
@PostalCode,
|
||||
@Coordinates)
|
||||
""",
|
||||
new
|
||||
{
|
||||
brewery.Location.BreweryPostLocationId,
|
||||
brewery.BreweryPostId,
|
||||
brewery.Location.CityId,
|
||||
brewery.Location.AddressLine1,
|
||||
brewery.Location.AddressLine2,
|
||||
brewery.Location.PostalCode,
|
||||
brewery.Location.Coordinates,
|
||||
},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
|
||||
return await GetByIdAsync(brewery.BreweryPostId)
|
||||
?? throw new InvalidOperationException(
|
||||
$"Brewery '{brewery.BreweryPostId}' was not found after a successful update."
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a brewery post by ID using the <c>USP_DeleteBrewery</c> stored procedure. Its location
|
||||
/// and photos are removed via cascading foreign keys.
|
||||
/// </summary>
|
||||
/// <inheritdoc/>
|
||||
public async Task DeleteAsync(Guid id)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "USP_DeleteBrewery";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
int rows = await connection.ExecuteAsync(
|
||||
"""
|
||||
DELETE FROM
|
||||
dbo.BreweryPost
|
||||
WHERE
|
||||
BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { BreweryPostId = id }
|
||||
);
|
||||
|
||||
AddParameter(command, "@BreweryPostID", id);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
if (rows == 0)
|
||||
throw new NotFoundException("Brewery not found.");
|
||||
}
|
||||
|
||||
/// <summary>Creates a new brewery post and its location using the <c>USP_CreateBrewery</c> stored procedure.</summary>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="brewery" />.<c>Location</c> is <c>null</c>.</exception>
|
||||
/// <inheritdoc/>
|
||||
public async Task CreateAsync(BreweryPost brewery)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
|
||||
command.CommandText = "USP_CreateBrewery";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
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.");
|
||||
|
||||
AddParameter(command, "@BreweryName", brewery.BreweryName);
|
||||
AddParameter(command, "@Description", brewery.Description);
|
||||
AddParameter(command, "@PostedByID", brewery.PostedById);
|
||||
AddParameter(command, "@CityID", brewery.Location?.CityId);
|
||||
AddParameter(command, "@AddressLine1", brewery.Location?.AddressLine1);
|
||||
AddParameter(command, "@AddressLine2", brewery.Location?.AddressLine2);
|
||||
AddParameter(command, "@PostalCode", brewery.Location?.PostalCode);
|
||||
AddParameter(command, "@Coordinates", brewery.Location?.Coordinates);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
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
|
||||
)
|
||||
)
|
||||
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
|
||||
)
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!cityExists)
|
||||
throw new NotFoundException("City not found.");
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.BreweryPost
|
||||
(BreweryPostID, BreweryName, Description, PostedByID)
|
||||
VALUES
|
||||
(@BreweryPostId, @BreweryName, @Description, @PostedById)
|
||||
""",
|
||||
new
|
||||
{
|
||||
brewery.BreweryPostId,
|
||||
brewery.BreweryName,
|
||||
brewery.Description,
|
||||
brewery.PostedById,
|
||||
},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
INSERT INTO dbo.BreweryPostLocation
|
||||
(BreweryPostLocationID,
|
||||
BreweryPostID,
|
||||
CityID,
|
||||
AddressLine1,
|
||||
AddressLine2,
|
||||
PostalCode,
|
||||
Coordinates)
|
||||
VALUES (@BreweryPostLocationId,
|
||||
@BreweryPostId,
|
||||
@CityId,
|
||||
@AddressLine1,
|
||||
@AddressLine2,
|
||||
@PostalCode,
|
||||
@Coordinates)
|
||||
""",
|
||||
new
|
||||
{
|
||||
brewery.Location.BreweryPostLocationId,
|
||||
brewery.BreweryPostId,
|
||||
brewery.Location.CityId,
|
||||
brewery.Location.AddressLine1,
|
||||
brewery.Location.AddressLine2,
|
||||
brewery.Location.PostalCode,
|
||||
brewery.Location.Coordinates,
|
||||
},
|
||||
transaction
|
||||
)
|
||||
);
|
||||
|
||||
await transaction.CommitAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current row of <paramref name="reader" /> to a <see cref="BreweryPost" />, including its
|
||||
/// associated <see cref="BreweryPostLocation" /> if location columns are present in the result set.
|
||||
/// Composes a joined row's <see cref="BreweryPost" />, <see cref="BreweryPostLocation" />,
|
||||
/// <see cref="City" />, <see cref="StateProvince" /> and <see cref="Country" /> fragments into a
|
||||
/// single populated <see cref="BreweryPost" />. When the row has no location (a left-joined
|
||||
/// brewery with no address on file), <paramref name="location" /> is a blank instance produced
|
||||
/// from all-<c>NULL</c> columns; the schema guarantees that whenever a location row was joined
|
||||
/// in, its City/StateProvince/Country chain was too.
|
||||
/// </summary>
|
||||
protected override BreweryPost MapToEntity(DbDataReader reader)
|
||||
private static BreweryPost MapBreweryRow(
|
||||
BreweryPost post,
|
||||
BreweryPostLocation location,
|
||||
City city,
|
||||
StateProvince stateProvince,
|
||||
Country country
|
||||
)
|
||||
{
|
||||
BreweryPost brewery = new();
|
||||
if (location.BreweryPostLocationId == Guid.Empty)
|
||||
return post;
|
||||
|
||||
int ordBreweryPostId = reader.GetOrdinal("BreweryPostId");
|
||||
int ordPostedById = reader.GetOrdinal("PostedById");
|
||||
int ordBreweryName = reader.GetOrdinal("BreweryName");
|
||||
int ordDescription = reader.GetOrdinal("Description");
|
||||
int ordCreatedAt = reader.GetOrdinal("CreatedAt");
|
||||
int ordUpdatedAt = reader.GetOrdinal("UpdatedAt");
|
||||
int ordTimer = reader.GetOrdinal("Timer");
|
||||
stateProvince.CountryId = country.CountryId;
|
||||
stateProvince.Country = country;
|
||||
|
||||
brewery.BreweryPostId = reader.GetGuid(ordBreweryPostId);
|
||||
brewery.PostedById = reader.GetGuid(ordPostedById);
|
||||
brewery.BreweryName = reader.GetString(ordBreweryName);
|
||||
brewery.Description = reader.GetString(ordDescription);
|
||||
brewery.CreatedAt = reader.GetDateTime(ordCreatedAt);
|
||||
city.StateProvinceId = stateProvince.StateProvinceId;
|
||||
city.StateProvince = stateProvince;
|
||||
|
||||
brewery.UpdatedAt = reader.IsDBNull(ordUpdatedAt) ? null : reader.GetDateTime(ordUpdatedAt);
|
||||
location.BreweryPostId = post.BreweryPostId;
|
||||
location.CityId = city.CityId;
|
||||
location.City = city;
|
||||
|
||||
// Read timer (varbinary/rowversion) robustly
|
||||
if (reader.IsDBNull(ordTimer))
|
||||
brewery.Timer = null;
|
||||
else
|
||||
try
|
||||
{
|
||||
brewery.Timer = reader.GetFieldValue<byte[]>(ordTimer);
|
||||
}
|
||||
catch
|
||||
{
|
||||
long length = reader.GetBytes(ordTimer, 0, null, 0, 0);
|
||||
byte[] buffer = new byte[length];
|
||||
reader.GetBytes(ordTimer, 0, buffer, 0, (int)length);
|
||||
brewery.Timer = buffer;
|
||||
}
|
||||
|
||||
// Map BreweryPostLocation if columns are present
|
||||
try
|
||||
{
|
||||
int ordLocationId = reader.GetOrdinal("BreweryPostLocationId");
|
||||
if (!reader.IsDBNull(ordLocationId))
|
||||
{
|
||||
BreweryPostLocation location = new()
|
||||
{
|
||||
BreweryPostLocationId = reader.GetGuid(ordLocationId),
|
||||
BreweryPostId = reader.GetGuid(reader.GetOrdinal("BreweryPostId")),
|
||||
CityId = reader.GetGuid(reader.GetOrdinal("CityId")),
|
||||
AddressLine1 = reader.GetString(reader.GetOrdinal("AddressLine1")),
|
||||
AddressLine2 = reader.IsDBNull(reader.GetOrdinal("AddressLine2"))
|
||||
? null
|
||||
: reader.GetString(reader.GetOrdinal("AddressLine2")),
|
||||
PostalCode = reader.GetString(reader.GetOrdinal("PostalCode")),
|
||||
Coordinates = reader.IsDBNull(reader.GetOrdinal("Coordinates"))
|
||||
? null
|
||||
: reader.GetFieldValue<byte[]>(reader.GetOrdinal("Coordinates")),
|
||||
};
|
||||
brewery.Location = location;
|
||||
}
|
||||
}
|
||||
catch (IndexOutOfRangeException)
|
||||
{
|
||||
// Location columns not present, skip mapping location
|
||||
}
|
||||
|
||||
return brewery;
|
||||
}
|
||||
|
||||
/// <summary>Adds a parameter to <paramref name="command" />, converting <c>null</c> to <see cref="DBNull.Value" />.</summary>
|
||||
private static void AddParameter(DbCommand command, string name, object? value)
|
||||
{
|
||||
DbParameter p = command.CreateParameter();
|
||||
p.ParameterName = name;
|
||||
p.Value = value ?? DBNull.Value;
|
||||
command.Parameters.Add(p);
|
||||
post.Location = location;
|
||||
return post;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,16 +7,45 @@ namespace Features.Breweries.Repository;
|
||||
/// </summary>
|
||||
public interface IBreweryRepository
|
||||
{
|
||||
/// <summary>Retrieves a brewery post by ID, or <c>null</c> if not found.</summary>
|
||||
/// <summary>
|
||||
/// Retrieves a brewery post by ID, joined to its location. Returns <c>null</c> if no brewery post
|
||||
/// exists with the given ID, or if it has no associated location.
|
||||
/// </summary>
|
||||
Task<BreweryPost?> GetByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all brewery posts, optionally paginated, ordered by creation date descending. Posts
|
||||
/// without a location are included, with <see cref="BreweryPost.Location" /> left <c>null</c>.
|
||||
/// </summary>
|
||||
/// <param name="limit">Maximum number of rows to return. Unbounded if <see langword="null" />.</param>
|
||||
/// <param name="offset">Number of rows to skip. Treated as zero if <see langword="null" />.</param>
|
||||
Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset);
|
||||
|
||||
Task UpdateAsync(BreweryPost brewery);
|
||||
/// <summary>
|
||||
/// Updates a brewery post's name and description, and upserts or clears its location, enforcing
|
||||
/// optimistic concurrency via <paramref name="brewery" />'s <c>RowVersion</c>: the update is rejected
|
||||
/// if the row was modified since <c>RowVersion</c> was read. When <paramref name="brewery" />'s
|
||||
/// <c>Location</c> is <c>null</c>, any existing location for the brewery is removed.
|
||||
/// Returns the freshly persisted brewery, including its new <c>RowVersion</c>.
|
||||
/// </summary>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">
|
||||
/// Thrown when no brewery exists with the given ID, or the given location's <c>CityId</c> does not
|
||||
/// exist.
|
||||
/// </exception>
|
||||
/// <exception cref="Domain.Exceptions.ConflictException">
|
||||
/// Thrown when <paramref name="brewery" />'s <c>RowVersion</c> no longer matches the stored row (it was
|
||||
/// modified by another request since it was last read).
|
||||
/// </exception>
|
||||
Task<BreweryPost> UpdateAsync(BreweryPost brewery);
|
||||
|
||||
/// <summary>Deletes a brewery post by ID. Its location and photos are removed via cascading foreign keys.</summary>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">Thrown when no brewery exists with the given <paramref name="id" />.</exception>
|
||||
Task DeleteAsync(Guid id);
|
||||
|
||||
/// <summary>Creates a new brewery post, including its location details.</summary>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="brewery" /> has no <c>Location</c>.</exception>
|
||||
/// <exception cref="Domain.Exceptions.NotFoundException">
|
||||
/// Thrown when <paramref name="brewery" />'s <c>PostedById</c> or <c>Location.CityId</c> does not exist.
|
||||
/// </exception>
|
||||
Task CreateAsync(BreweryPost brewery);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.9.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -5,8 +5,15 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Features.Emails.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services used by the Features.Emails slice.
|
||||
/// </summary>
|
||||
public static class FeaturesEmailsServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the SMTP email provider, template renderer, and <see cref="IEmailDispatcher" />.
|
||||
/// </summary>
|
||||
/// <returns>The same <paramref name="services" /> instance, for chaining.</returns>
|
||||
public static IServiceCollection AddFeaturesEmails(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IEmailProvider, SmtpEmailProvider>();
|
||||
|
||||
@@ -22,6 +22,7 @@ public class EmailDispatcher(
|
||||
Environment.GetEnvironmentVariable("WEBSITE_BASE_URL")
|
||||
?? throw new InvalidOperationException("WEBSITE_BASE_URL environment variable is not set");
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SendRegistrationEmailAsync(
|
||||
string firstName,
|
||||
string email,
|
||||
@@ -38,6 +39,7 @@ public class EmailDispatcher(
|
||||
await emailProvider.SendAsync(email, "Welcome to The Biergarten App!", emailHtml, true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SendResendConfirmationEmailAsync(
|
||||
string firstName,
|
||||
string email,
|
||||
|
||||
@@ -8,10 +8,14 @@ public interface IEmailDispatcher
|
||||
/// <summary>
|
||||
/// Sends a welcome email containing an account confirmation link to a newly registered user.
|
||||
/// </summary>
|
||||
/// <remarks>The email is sent synchronously; the returned task completes once delivery to the mail server succeeds or fails.</remarks>
|
||||
/// <param name="confirmationToken">Embedded in the confirmation link sent to <paramref name="email" />.</param>
|
||||
Task SendRegistrationEmailAsync(string firstName, string email, string confirmationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Sends an email containing a fresh account confirmation link to a user who requested a resend.
|
||||
/// </summary>
|
||||
/// <remarks>The email is sent synchronously; the returned task completes once delivery to the mail server succeeds or fails.</remarks>
|
||||
/// <param name="confirmationToken">Embedded in the confirmation link sent to <paramref name="email" />.</param>
|
||||
Task SendResendConfirmationEmailAsync(string firstName, string email, string confirmationToken);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<RootNamespace>Features.Locations.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Features.Locations\Features.Locations.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,20 @@
|
||||
using Features.Locations.Repository;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Features.Locations.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services used by the Features.Locations slice.
|
||||
/// </summary>
|
||||
public static class FeaturesLocationsServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers <see cref="ILocationRepository" /> and its Dapper-based implementation.
|
||||
/// </summary>
|
||||
/// <returns>The same <paramref name="services" /> instance, for chaining.</returns>
|
||||
public static IServiceCollection AddFeaturesLocations(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<ILocationRepository, LocationRepository>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
13
web/backend/Features/Features.Locations/Dtos/CityLocation.cs
Normal file
13
web/backend/Features/Features.Locations/Dtos/CityLocation.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace Features.Locations.Dtos;
|
||||
|
||||
/// <summary>
|
||||
/// Describes a city's location for resolution by <c>ILocationRepository</c>, including the
|
||||
/// state/province and country it belongs to.
|
||||
/// </summary>
|
||||
public sealed record CityLocation(
|
||||
string CityName,
|
||||
string StateProvinceName,
|
||||
string StateProvinceIsoCode,
|
||||
string CountryName,
|
||||
string CountryIsoCode
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Features.Locations</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
|
||||
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
|
||||
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,16 @@
|
||||
using Features.Locations.Dtos;
|
||||
|
||||
namespace Features.Locations.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the Country/StateProvince/City location hierarchy shared by features that attach a
|
||||
/// location to a record (e.g. brewery posts, and eventually user accounts).
|
||||
/// </summary>
|
||||
public interface ILocationRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves <paramref name="location" /> to a City ID, creating the Country, StateProvince,
|
||||
/// and/or City rows if any part of the chain doesn't exist yet.
|
||||
/// </summary>
|
||||
Task<Guid> GetOrCreateCityIdAsync(CityLocation location);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using System.Data.Common;
|
||||
using Dapper;
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.Locations.Dtos;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.Locations.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// Dapper-based implementation of <see cref="ILocationRepository" />.
|
||||
/// </summary>
|
||||
public class LocationRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<City>(connectionFactory),
|
||||
ILocationRepository
|
||||
{
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Not fully race-safe under concurrent callers for the same new city (neither was the stored
|
||||
/// procedure this replaces, since <c>City</c> has no unique constraint on name+state): a
|
||||
/// concurrent duplicate insert can succeed rather than being rejected. Country/StateProvince
|
||||
/// creation guards against this the same way the original stored procedures did, via an
|
||||
/// existence pre-check immediately before the insert.
|
||||
/// </remarks>
|
||||
public async Task<Guid> GetOrCreateCityIdAsync(CityLocation location)
|
||||
{
|
||||
await EnsureCountryExistsAsync(location.CountryName, location.CountryIsoCode);
|
||||
await EnsureStateProvinceExistsAsync(
|
||||
location.StateProvinceName,
|
||||
location.StateProvinceIsoCode,
|
||||
location.CountryIsoCode
|
||||
);
|
||||
|
||||
Guid? cityId = await GetCityIdAsync(location.CityName, location.StateProvinceIsoCode);
|
||||
if (cityId is not null)
|
||||
return cityId.Value;
|
||||
|
||||
Guid stateProvinceId =
|
||||
await GetStateProvinceIdAsync(location.StateProvinceIsoCode)
|
||||
?? throw new NotFoundException(
|
||||
$"State/province '{location.StateProvinceIsoCode}' not found."
|
||||
);
|
||||
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
|
||||
bool cityExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.City
|
||||
WHERE CityName = @CityName AND StateProvinceID = @StateProvinceId
|
||||
""",
|
||||
new { location.CityName, StateProvinceId = stateProvinceId }
|
||||
) is not null;
|
||||
|
||||
if (!cityExists)
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO dbo.City (StateProvinceID, CityName)
|
||||
VALUES (@StateProvinceId, @CityName)
|
||||
""",
|
||||
new { StateProvinceId = stateProvinceId, location.CityName }
|
||||
);
|
||||
|
||||
return await GetCityIdAsync(location.CityName, location.StateProvinceIsoCode)
|
||||
?? throw new InvalidOperationException(
|
||||
$"City '{location.CityName}' was not found after creation."
|
||||
);
|
||||
}
|
||||
|
||||
private async Task EnsureCountryExistsAsync(string countryName, string isoCode)
|
||||
{
|
||||
if (await GetCountryIdAsync(isoCode) is not null)
|
||||
return;
|
||||
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
|
||||
bool exists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.Country
|
||||
WHERE ISO3166_1 = @ISO3166_1
|
||||
""",
|
||||
new { ISO3166_1 = isoCode }
|
||||
) is not null;
|
||||
|
||||
if (!exists)
|
||||
// A concurrent caller may create this country between the check above and here; that
|
||||
// race is tolerated (the resulting duplicate row, if any, is out of scope for this method).
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO dbo.Country (CountryName, ISO3166_1)
|
||||
VALUES (@CountryName, @ISO3166_1)
|
||||
""",
|
||||
new { CountryName = countryName, ISO3166_1 = isoCode }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures a StateProvince row exists for <paramref name="isoCode" />.
|
||||
/// </summary>
|
||||
/// <exception cref="NotFoundException">
|
||||
/// Thrown when no Country exists for <paramref name="countryIsoCode" />. Not expected in normal
|
||||
/// operation, since callers ensure the Country exists first — retained as a defensive translation
|
||||
/// in case of a race between concurrent callers.
|
||||
/// </exception>
|
||||
private async Task EnsureStateProvinceExistsAsync(
|
||||
string stateProvinceName,
|
||||
string isoCode,
|
||||
string countryIsoCode
|
||||
)
|
||||
{
|
||||
if (await GetStateProvinceIdAsync(isoCode) is not null)
|
||||
return;
|
||||
|
||||
Guid countryId =
|
||||
await GetCountryIdAsync(countryIsoCode)
|
||||
?? throw new NotFoundException($"Country '{countryIsoCode}' not found.");
|
||||
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
|
||||
bool exists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.StateProvince
|
||||
WHERE ISO3166_2 = @ISO3166_2
|
||||
""",
|
||||
new { ISO3166_2 = isoCode }
|
||||
) is not null;
|
||||
|
||||
if (!exists)
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO dbo.StateProvince (StateProvinceName, ISO3166_2, CountryID)
|
||||
VALUES (@StateProvinceName, @ISO3166_2, @CountryId)
|
||||
""",
|
||||
new
|
||||
{
|
||||
StateProvinceName = stateProvinceName,
|
||||
ISO3166_2 = isoCode,
|
||||
CountryId = countryId,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private async Task<Guid?> GetCountryIdAsync(string isoCode)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<Guid?>(
|
||||
"""
|
||||
SELECT CountryID
|
||||
FROM dbo.Country
|
||||
WHERE ISO3166_1 = @ISO3166_1
|
||||
""",
|
||||
new { ISO3166_1 = isoCode }
|
||||
);
|
||||
}
|
||||
|
||||
private async Task<Guid?> GetStateProvinceIdAsync(string isoCode)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<Guid?>(
|
||||
"""
|
||||
SELECT StateProvinceID
|
||||
FROM dbo.StateProvince
|
||||
WHERE ISO3166_2 = @ISO3166_2
|
||||
""",
|
||||
new { ISO3166_2 = isoCode }
|
||||
);
|
||||
}
|
||||
|
||||
private async Task<Guid?> GetCityIdAsync(string cityName, string stateProvinceIsoCode)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<Guid?>(
|
||||
"""
|
||||
SELECT c.CityID
|
||||
FROM dbo.City c
|
||||
INNER JOIN dbo.StateProvince sp ON sp.StateProvinceID = c.StateProvinceID
|
||||
WHERE c.CityName = @CityName AND sp.ISO3166_2 = @StateProvinceCode
|
||||
""",
|
||||
new { CityName = cityName, StateProvinceCode = stateProvinceIsoCode }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,7 @@
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.9.0" />
|
||||
<PackageReference Include="DbMocker" Version="1.26.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
using System.Data.Common;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.UserManagement.Tests.Repository;
|
||||
|
||||
internal class TestConnectionFactory(DbConnection conn) : ISqlConnectionFactory
|
||||
{
|
||||
private readonly DbConnection _conn = conn;
|
||||
|
||||
public DbConnection CreateConnection()
|
||||
{
|
||||
return _conn;
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
using Apps72.Dev.Data.DbMocker;
|
||||
using Domain.Entities;
|
||||
using Features.UserManagement.Repository;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace Features.UserManagement.Tests.Repository;
|
||||
|
||||
public class UserAccountRepositoryTests
|
||||
{
|
||||
private static UserAccountRepository CreateRepo(MockDbConnection conn)
|
||||
{
|
||||
return new UserAccountRepository(new TestConnectionFactory(conn));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsRow_Mapped()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountById")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
|
||||
"yerb",
|
||||
"Aaron",
|
||||
"Po",
|
||||
"aaronpo@example.com",
|
||||
new DateTime(2020, 1, 1),
|
||||
null,
|
||||
new DateTime(1990, 1, 1),
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
UserAccountRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetByIdAsync(
|
||||
Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
|
||||
);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Username.Should().Be("yerb");
|
||||
result.Email.Should().Be("aaronpo@example.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_ReturnsMultipleRows()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetAllUserAccounts")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
Guid.NewGuid(),
|
||||
"a",
|
||||
"A",
|
||||
"A",
|
||||
"a@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
DateTime.UtcNow.Date,
|
||||
null
|
||||
)
|
||||
.AddRow(
|
||||
Guid.NewGuid(),
|
||||
"b",
|
||||
"B",
|
||||
"B",
|
||||
"b@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
DateTime.UtcNow.Date,
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
UserAccountRepository repo = CreateRepo(conn);
|
||||
List<UserAccount> results = (await repo.GetAllAsync(null, null)).ToList();
|
||||
results.Should().HaveCount(2);
|
||||
results.Select(r => r.Username).Should().BeEquivalentTo("a", "b");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByUsername_ReturnsRow()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByUsername")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
Guid.NewGuid(),
|
||||
"lookupuser",
|
||||
"L",
|
||||
"U",
|
||||
"lookup@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
DateTime.UtcNow.Date,
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
UserAccountRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetByUsernameAsync("lookupuser");
|
||||
result.Should().NotBeNull();
|
||||
result!.Email.Should().Be("lookup@example.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByEmail_ReturnsRow()
|
||||
{
|
||||
MockDbConnection conn = new();
|
||||
conn.Mocks.When(cmd => cmd.CommandText == "usp_GetUserAccountByEmail")
|
||||
.ReturnsTable(
|
||||
MockTable
|
||||
.WithColumns(
|
||||
("UserAccountId", typeof(Guid)),
|
||||
("Username", typeof(string)),
|
||||
("FirstName", typeof(string)),
|
||||
("LastName", typeof(string)),
|
||||
("Email", typeof(string)),
|
||||
("CreatedAt", typeof(DateTime)),
|
||||
("UpdatedAt", typeof(DateTime?)),
|
||||
("DateOfBirth", typeof(DateTime)),
|
||||
("Timer", typeof(byte[]))
|
||||
)
|
||||
.AddRow(
|
||||
Guid.NewGuid(),
|
||||
"byemail",
|
||||
"B",
|
||||
"E",
|
||||
"byemail@example.com",
|
||||
DateTime.UtcNow,
|
||||
null,
|
||||
DateTime.UtcNow.Date,
|
||||
null
|
||||
)
|
||||
);
|
||||
|
||||
UserAccountRepository repo = CreateRepo(conn);
|
||||
UserAccount? result = await repo.GetByEmailAsync("byemail@example.com");
|
||||
result.Should().NotBeNull();
|
||||
result!.Username.Should().Be("byemail");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@ using MediatR;
|
||||
|
||||
namespace Features.UserManagement.Commands.UpdateUser;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="UpdateUserCommand" />.
|
||||
/// </summary>
|
||||
public class UpdateUserHandler(IUserAccountRepository repository)
|
||||
: IRequestHandler<UpdateUserCommand>
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Features.UserManagement.Queries.GetAllUsers;
|
||||
using Features.UserManagement.Queries.GetUserById;
|
||||
using MediatR;
|
||||
@@ -6,10 +7,14 @@ using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Features.UserManagement.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Exposes read endpoints for user accounts.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class UserController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
/// <summary>Gets a page of user accounts, ordered by creation date descending.</summary>
|
||||
/// <param name="limit"><c>null</c> for no limit.</param>
|
||||
/// <param name="offset"><c>null</c> for no offset.</param>
|
||||
[HttpGet]
|
||||
@@ -22,6 +27,10 @@ public class UserController(IMediator mediator) : ControllerBase
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
/// <summary>Gets the user account with the given ID.</summary>
|
||||
/// <exception cref="NotFoundException">
|
||||
/// Thrown when no user account exists with the given ID, resulting in a 404 response.
|
||||
/// </exception>
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<UserAccount>> GetById(Guid id)
|
||||
{
|
||||
|
||||
@@ -3,8 +3,15 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Features.UserManagement.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services used by the Features.UserManagement slice.
|
||||
/// </summary>
|
||||
public static class FeaturesUserManagementServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers <see cref="IUserAccountRepository" /> and its Dapper-based implementation.
|
||||
/// </summary>
|
||||
/// <returns>The same <paramref name="services" /> instance, for chaining.</returns>
|
||||
public static IServiceCollection AddFeaturesUserManagement(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<IUserAccountRepository, UserAccountRepository>();
|
||||
|
||||
@@ -4,6 +4,9 @@ using MediatR;
|
||||
|
||||
namespace Features.UserManagement.Queries.GetAllUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="GetAllUsersQuery" />.
|
||||
/// </summary>
|
||||
public class GetAllUsersHandler(IUserAccountRepository repository)
|
||||
: IRequestHandler<GetAllUsersQuery, IEnumerable<UserAccount>>
|
||||
{
|
||||
|
||||
@@ -3,4 +3,9 @@ using MediatR;
|
||||
|
||||
namespace Features.UserManagement.Queries.GetAllUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Requests a page of user accounts, ordered by creation date descending.
|
||||
/// </summary>
|
||||
/// <param name="Limit"><c>null</c> for no limit.</param>
|
||||
/// <param name="Offset"><c>null</c> for no offset.</param>
|
||||
public record GetAllUsersQuery(int? Limit, int? Offset) : IRequest<IEnumerable<UserAccount>>;
|
||||
|
||||
@@ -5,6 +5,9 @@ using MediatR;
|
||||
|
||||
namespace Features.UserManagement.Queries.GetUserById;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="GetUserByIdQuery" />.
|
||||
/// </summary>
|
||||
public class GetUserByIdHandler(IUserAccountRepository repository)
|
||||
: IRequestHandler<GetUserByIdQuery, UserAccount>
|
||||
{
|
||||
|
||||
@@ -3,4 +3,7 @@ using MediatR;
|
||||
|
||||
namespace Features.UserManagement.Queries.GetUserById;
|
||||
|
||||
/// <summary>
|
||||
/// Requests the user account with the given ID.
|
||||
/// </summary>
|
||||
public record GetUserByIdQuery(Guid UserAccountId) : IRequest<UserAccount>;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
|
||||
namespace Features.UserManagement.Repository;
|
||||
|
||||
@@ -7,30 +8,26 @@ namespace Features.UserManagement.Repository;
|
||||
/// </summary>
|
||||
public interface IUserAccountRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a user account by its unique identifier, or <c>null</c> if not found.
|
||||
/// </summary>
|
||||
/// <summary>Returns <c>null</c> if no user account exists with the given ID.</summary>
|
||||
Task<UserAccount?> GetByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all user accounts, optionally paginated.
|
||||
/// </summary>
|
||||
/// <summary>Returns user accounts ordered by creation date descending.</summary>
|
||||
/// <param name="limit"><c>null</c> for no limit.</param>
|
||||
/// <param name="offset"><c>null</c> for no offset.</param>
|
||||
Task<IEnumerable<UserAccount>> GetAllAsync(int? limit, int? offset);
|
||||
|
||||
/// <summary>Updates the mutable fields of an existing user account.</summary>
|
||||
/// <param name="userAccount">Must have a valid <c>UserAccountId</c>.</param>
|
||||
/// <exception cref="NotFoundException">Thrown when no user account exists with the given ID.</exception>
|
||||
Task UpdateAsync(UserAccount userAccount);
|
||||
|
||||
/// <summary>Deletes the user account with the given ID.</summary>
|
||||
/// <exception cref="NotFoundException">Thrown when no user account exists with the given ID.</exception>
|
||||
Task DeleteAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by username, or <c>null</c> if not found.
|
||||
/// </summary>
|
||||
/// <summary>Returns <c>null</c> if no user account exists with the given username.</summary>
|
||||
Task<UserAccount?> GetByUsernameAsync(string username);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by email address, or <c>null</c> if not found.
|
||||
/// </summary>
|
||||
/// <summary>Returns <c>null</c> if no user account exists with the given email address.</summary>
|
||||
Task<UserAccount?> GetByEmailAsync(string email);
|
||||
}
|
||||
|
||||
@@ -1,149 +1,118 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using Dapper;
|
||||
using Domain.Entities;
|
||||
using Domain.Exceptions;
|
||||
using Infrastructure.Sql;
|
||||
|
||||
namespace Features.UserManagement.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IUserAccountRepository" /> backed by SQL Server
|
||||
/// stored procedures.
|
||||
/// Dapper-based implementation of <see cref="IUserAccountRepository" />.
|
||||
/// </summary>
|
||||
public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<UserAccount>(connectionFactory),
|
||||
IUserAccountRepository
|
||||
{
|
||||
/// <summary>Uses the <c>usp_GetUserAccountById</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetByIdAsync(Guid id)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountById";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@UserAccountId", id);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE UserAccountID = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = id }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uses the <c>usp_GetAllUserAccounts</c> stored procedure. The <c>@Limit</c> and <c>@Offset</c>
|
||||
/// parameters are only added when their corresponding argument has a value.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Always applies pagination via <c>OFFSET</c>/<c>FETCH</c>, ordered by creation date descending.
|
||||
/// A <c>null</c> <paramref name="limit" />/<paramref name="offset" /> is treated as "no limit"/"no offset".
|
||||
/// </remarks>
|
||||
public async Task<IEnumerable<UserAccount>> GetAllAsync(int? limit, int? offset)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetAllUserAccounts";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
if (limit.HasValue)
|
||||
AddParameter(command, "@Limit", limit.Value);
|
||||
|
||||
if (offset.HasValue)
|
||||
AddParameter(command, "@Offset", offset.Value);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
List<UserAccount> users = new();
|
||||
|
||||
while (await reader.ReadAsync())
|
||||
users.Add(MapToEntity(reader));
|
||||
|
||||
return users;
|
||||
return await connection.QueryAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
ORDER BY CreatedAt DESC
|
||||
OFFSET @Offset ROWS FETCH NEXT @Limit ROWS ONLY
|
||||
""",
|
||||
new { Offset = offset ?? 0, Limit = limit ?? int.MaxValue }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a user account's username, first name, last name, email, and date of birth using
|
||||
/// the <c>usp_UpdateUserAccount</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public async Task UpdateAsync(UserAccount userAccount)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_UpdateUserAccount";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
int rows = await connection.ExecuteAsync(
|
||||
"""
|
||||
UPDATE dbo.UserAccount
|
||||
SET Username = @Username, FirstName = @FirstName, LastName = @LastName,
|
||||
DateOfBirth = @DateOfBirth, Email = @Email
|
||||
WHERE UserAccountId = @UserAccountId
|
||||
""",
|
||||
new
|
||||
{
|
||||
UserAccountId = userAccount.UserAccountId,
|
||||
userAccount.Username,
|
||||
userAccount.FirstName,
|
||||
userAccount.LastName,
|
||||
userAccount.DateOfBirth,
|
||||
userAccount.Email,
|
||||
}
|
||||
);
|
||||
|
||||
AddParameter(command, "@UserAccountId", userAccount.UserAccountId);
|
||||
AddParameter(command, "@Username", userAccount.Username);
|
||||
AddParameter(command, "@FirstName", userAccount.FirstName);
|
||||
AddParameter(command, "@LastName", userAccount.LastName);
|
||||
AddParameter(command, "@Email", userAccount.Email);
|
||||
AddParameter(command, "@DateOfBirth", userAccount.DateOfBirth);
|
||||
|
||||
await command.ExecuteNonQueryAsync();
|
||||
if (rows == 0)
|
||||
throw new NotFoundException("User account not found.");
|
||||
}
|
||||
|
||||
/// <summary>Uses the <c>usp_DeleteUserAccount</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task DeleteAsync(Guid id)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_DeleteUserAccount";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
int rows = await connection.ExecuteAsync(
|
||||
"""
|
||||
DELETE FROM dbo.UserAccount
|
||||
WHERE UserAccountId = @UserAccountId
|
||||
""",
|
||||
new { UserAccountId = id }
|
||||
);
|
||||
|
||||
AddParameter(command, "@UserAccountId", id);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
if (rows == 0)
|
||||
throw new NotFoundException("User account not found.");
|
||||
}
|
||||
|
||||
/// <summary>Uses the <c>usp_GetUserAccountByUsername</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetByUsernameAsync(string username)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountByUsername";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@Username", username);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE Username = @Username
|
||||
""",
|
||||
new { Username = username }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Uses the <c>usp_GetUserAccountByEmail</c> stored procedure.</summary>
|
||||
/// <inheritdoc />
|
||||
public async Task<UserAccount?> GetByEmailAsync(string email)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbCommand command = connection.CreateCommand();
|
||||
command.CommandText = "usp_GetUserAccountByEmail";
|
||||
command.CommandType = CommandType.StoredProcedure;
|
||||
|
||||
AddParameter(command, "@Email", email);
|
||||
|
||||
await using DbDataReader reader = await command.ExecuteReaderAsync();
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
protected override UserAccount MapToEntity(DbDataReader reader)
|
||||
{
|
||||
return new UserAccount
|
||||
{
|
||||
UserAccountId = reader.GetGuid(reader.GetOrdinal("UserAccountId")),
|
||||
Username = reader.GetString(reader.GetOrdinal("Username")),
|
||||
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
|
||||
LastName = reader.GetString(reader.GetOrdinal("LastName")),
|
||||
Email = reader.GetString(reader.GetOrdinal("Email")),
|
||||
CreatedAt = reader.GetDateTime(reader.GetOrdinal("CreatedAt")),
|
||||
UpdatedAt = reader.IsDBNull(reader.GetOrdinal("UpdatedAt"))
|
||||
? null
|
||||
: reader.GetDateTime(reader.GetOrdinal("UpdatedAt")),
|
||||
DateOfBirth = reader.GetDateTime(reader.GetOrdinal("DateOfBirth")),
|
||||
Timer = reader.IsDBNull(reader.GetOrdinal("Timer")) ? null : (byte[])reader["Timer"],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Converts <c>null</c> values to <see cref="DBNull.Value" /> when adding the parameter.</summary>
|
||||
private static void AddParameter(DbCommand command, string name, object? value)
|
||||
{
|
||||
DbParameter p = command.CreateParameter();
|
||||
p.ParameterName = name;
|
||||
p.Value = value ?? DBNull.Value;
|
||||
command.Parameters.Add(p);
|
||||
return await connection.QueryFirstOrDefaultAsync<UserAccount>(
|
||||
"""
|
||||
SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion
|
||||
FROM dbo.UserAccount
|
||||
WHERE Email = @Email
|
||||
""",
|
||||
new { Email = email }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user