mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-07-16 17:47:22 +00:00
add xmldoc comments
This commit is contained in:
@@ -8,6 +8,8 @@ namespace Infrastructure.Email.Templates.Rendering;
|
||||
/// <summary>
|
||||
/// Service for rendering Razor email templates to HTML using HtmlRenderer.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider used to resolve dependencies for the Razor component rendering pipeline.</param>
|
||||
/// <param name="loggerFactory">The logger factory passed to the <see cref="HtmlRenderer"/> used to render components.</param>
|
||||
public class EmailTemplateProvider(
|
||||
IServiceProvider serviceProvider,
|
||||
ILoggerFactory loggerFactory
|
||||
@@ -16,6 +18,9 @@ public class EmailTemplateProvider(
|
||||
/// <summary>
|
||||
/// Renders the UserRegisteredEmail template with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to include in the email</param>
|
||||
/// <param name="confirmationLink">The email confirmation link</param>
|
||||
/// <returns>The rendered HTML string</returns>
|
||||
public async Task<string> RenderUserRegisteredEmailAsync(
|
||||
string username,
|
||||
string confirmationLink
|
||||
@@ -33,6 +38,9 @@ public class EmailTemplateProvider(
|
||||
/// <summary>
|
||||
/// Renders the ResendConfirmation template with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to include in the email</param>
|
||||
/// <param name="confirmationLink">The new confirmation link</param>
|
||||
/// <returns>The rendered HTML string</returns>
|
||||
public async Task<string> RenderResendConfirmationEmailAsync(
|
||||
string username,
|
||||
string confirmationLink
|
||||
@@ -49,7 +57,12 @@ public class EmailTemplateProvider(
|
||||
|
||||
/// <summary>
|
||||
/// Generic method to render any Razor component to HTML.
|
||||
/// Creates a scoped <see cref="HtmlRenderer"/>, dispatches the render onto its renderer thread,
|
||||
/// and returns the resulting HTML string.
|
||||
/// </summary>
|
||||
/// <typeparam name="TComponent">The type of the Razor component to render.</typeparam>
|
||||
/// <param name="parameters">A dictionary of parameter names and values to pass to the component.</param>
|
||||
/// <returns>The rendered HTML string for the component.</returns>
|
||||
private async Task<string> RenderComponentAsync<TComponent>(
|
||||
Dictionary<string, object?> parameters
|
||||
)
|
||||
|
||||
@@ -18,6 +18,25 @@ public class SmtpEmailProvider : IEmailProvider
|
||||
private readonly string _fromEmail;
|
||||
private readonly string _fromName;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="SmtpEmailProvider"/>, reading SMTP configuration
|
||||
/// from environment variables.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Reads the following environment variables:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><c>SMTP_HOST</c> (required) - the SMTP server hostname.</description></item>
|
||||
/// <item><description><c>SMTP_PORT</c> (optional, default "587") - the SMTP server port, must be a valid integer.</description></item>
|
||||
/// <item><description><c>SMTP_USERNAME</c> (optional) - the username used for authentication.</description></item>
|
||||
/// <item><description><c>SMTP_PASSWORD</c> (optional) - the password used for authentication.</description></item>
|
||||
/// <item><description><c>SMTP_USE_SSL</c> (optional, default "true") - whether to use StartTls when connecting.</description></item>
|
||||
/// <item><description><c>SMTP_FROM_EMAIL</c> (required) - the email address used as the sender.</description></item>
|
||||
/// <item><description><c>SMTP_FROM_NAME</c> (optional, default "The Biergarten") - the display name used as the sender.</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Thrown when <c>SMTP_HOST</c> or <c>SMTP_FROM_EMAIL</c> is not set, or when <c>SMTP_PORT</c> is not a valid integer.
|
||||
/// </exception>
|
||||
public SmtpEmailProvider()
|
||||
{
|
||||
_host =
|
||||
@@ -53,6 +72,14 @@ public class SmtpEmailProvider : IEmailProvider
|
||||
?? "The Biergarten";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends an email to a single recipient by delegating to the multi-recipient overload.
|
||||
/// </summary>
|
||||
/// <param name="to">Recipient email address</param>
|
||||
/// <param name="subject">Email subject line</param>
|
||||
/// <param name="body">Email body (HTML or plain text)</param>
|
||||
/// <param name="isHtml">Whether the body is HTML (default: true)</param>
|
||||
/// <exception cref="InvalidOperationException">Thrown when connecting, authenticating, or sending via SMTP fails.</exception>
|
||||
public async Task SendAsync(
|
||||
string to,
|
||||
string subject,
|
||||
@@ -63,6 +90,16 @@ public class SmtpEmailProvider : IEmailProvider
|
||||
await SendAsync([to], subject, body, isHtml);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends an email to multiple recipients using MailKit's <see cref="SmtpClient"/>.
|
||||
/// Connects using StartTls when SSL is enabled (or no encryption otherwise), authenticates
|
||||
/// if credentials were configured, sends the message, and disconnects.
|
||||
/// </summary>
|
||||
/// <param name="to">List of recipient email addresses</param>
|
||||
/// <param name="subject">Email subject line</param>
|
||||
/// <param name="body">Email body (HTML or plain text)</param>
|
||||
/// <param name="isHtml">Whether the body is HTML (default: true)</param>
|
||||
/// <exception cref="InvalidOperationException">Thrown when connecting, authenticating, or sending via SMTP fails. The original exception is included as the inner exception.</exception>
|
||||
public async Task SendAsync(
|
||||
IEnumerable<string> to,
|
||||
string subject,
|
||||
|
||||
@@ -2,8 +2,19 @@ using System.Security.Claims;
|
||||
|
||||
namespace Infrastructure.Jwt;
|
||||
|
||||
/// <summary>
|
||||
/// Service for generating and validating JSON Web Tokens (JWTs) used for authentication.
|
||||
/// </summary>
|
||||
public interface ITokenInfrastructure
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a signed JWT for the given user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the user the token is issued for.</param>
|
||||
/// <param name="username">The username of the user, included as a claim.</param>
|
||||
/// <param name="expiry">The date and time at which the token expires.</param>
|
||||
/// <param name="secret">The symmetric secret used to sign the token.</param>
|
||||
/// <returns>The serialized, signed JWT string.</returns>
|
||||
string GenerateJwt(
|
||||
Guid userId,
|
||||
string username,
|
||||
@@ -11,5 +22,12 @@ public interface ITokenInfrastructure
|
||||
string secret
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Validates a JWT and returns the resulting claims principal.
|
||||
/// </summary>
|
||||
/// <param name="token">The JWT string to validate.</param>
|
||||
/// <param name="secret">The symmetric secret used to verify the token's signature.</param>
|
||||
/// <returns>A <see cref="ClaimsPrincipal"/> representing the validated token's claims.</returns>
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">Thrown when the token is invalid, expired, or fails validation.</exception>
|
||||
Task<ClaimsPrincipal> ValidateJwtAsync(string token, string secret);
|
||||
}
|
||||
@@ -7,8 +7,24 @@ using Domain.Exceptions;
|
||||
|
||||
namespace Infrastructure.Jwt;
|
||||
|
||||
/// <summary>
|
||||
/// Generates and validates HMAC-SHA256 signed JWTs using <see cref="JsonWebTokenHandler"/>.
|
||||
/// </summary>
|
||||
public class JwtInfrastructure : ITokenInfrastructure
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a signed JWT containing the user's ID, username, issued-at time, expiry time,
|
||||
/// and a unique token identifier (JTI), signed using HMAC-SHA256 with the provided secret.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sets the following registered claims: <c>sub</c> (userId), <c>unique_name</c> (username),
|
||||
/// <c>iat</c> (current UTC time), <c>exp</c> (expiry), and <c>jti</c> (a newly generated GUID).
|
||||
/// </remarks>
|
||||
/// <param name="userId">The unique identifier of the user the token is issued for.</param>
|
||||
/// <param name="username">The username of the user, included as a claim.</param>
|
||||
/// <param name="expiry">The date and time at which the token expires.</param>
|
||||
/// <param name="secret">The symmetric secret used to sign the token (encoded as UTF-8 bytes).</param>
|
||||
/// <returns>The serialized, signed JWT string.</returns>
|
||||
public string GenerateJwt(
|
||||
Guid userId,
|
||||
string username,
|
||||
@@ -47,6 +63,17 @@ public class JwtInfrastructure : ITokenInfrastructure
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Validates a JWT's signature and lifetime (issuer and audience validation are disabled),
|
||||
/// using the provided secret as the HMAC-SHA256 symmetric signing key.
|
||||
/// </summary>
|
||||
/// <param name="token">The JWT string to validate.</param>
|
||||
/// <param name="secret">The symmetric secret used to verify the token's signature (encoded as UTF-8 bytes).</param>
|
||||
/// <returns>A <see cref="ClaimsPrincipal"/> wrapping the validated token's claims identity.</returns>
|
||||
/// <exception cref="UnauthorizedException">
|
||||
/// Thrown when the token is invalid, has no claims identity, is expired, or otherwise fails validation
|
||||
/// (including when validation itself throws, e.g. due to a malformed token or signature mismatch).
|
||||
/// </exception>
|
||||
public async Task<ClaimsPrincipal> ValidateJwtAsync(
|
||||
string token,
|
||||
string secret
|
||||
|
||||
@@ -4,6 +4,9 @@ using Konscious.Security.Cryptography;
|
||||
|
||||
namespace Infrastructure.PasswordHashing;
|
||||
|
||||
/// <summary>
|
||||
/// Hashes and verifies passwords using the Argon2id algorithm via Konscious.Security.Cryptography.
|
||||
/// </summary>
|
||||
public class Argon2Infrastructure : IPasswordInfrastructure
|
||||
{
|
||||
private const int SaltSize = 16; // 128-bit
|
||||
@@ -11,6 +14,16 @@ public class Argon2Infrastructure : IPasswordInfrastructure
|
||||
private const int ArgonIterations = 4;
|
||||
private const int ArgonMemoryKb = 65536; // 64MB
|
||||
|
||||
/// <summary>
|
||||
/// Hashes a plaintext password using Argon2id with a newly generated 128-bit cryptographically
|
||||
/// random salt, 4 iterations, 64MB of memory, and a degree of parallelism equal to the number of
|
||||
/// available processors (minimum 1).
|
||||
/// </summary>
|
||||
/// <param name="password">The plaintext password to hash.</param>
|
||||
/// <returns>
|
||||
/// A string of the form <c>"{base64Salt}:{base64Hash}"</c> containing the salt and the resulting
|
||||
/// 256-bit hash, suitable for storage and later verification.
|
||||
/// </returns>
|
||||
public string Hash(string password)
|
||||
{
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltSize);
|
||||
@@ -26,6 +39,20 @@ public class Argon2Infrastructure : IPasswordInfrastructure
|
||||
return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a plaintext password against a stored salt/hash string by recomputing the Argon2id
|
||||
/// hash with the extracted salt and comparing it to the stored hash using a fixed-time comparison
|
||||
/// to mitigate timing attacks.
|
||||
/// </summary>
|
||||
/// <param name="password">The plaintext password to verify.</param>
|
||||
/// <param name="stored">
|
||||
/// The stored string of the form <c>"{base64Salt}:{base64Hash}"</c> previously produced by <see cref="Hash"/>.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the password matches the stored hash; <c>false</c> if it does not match, the stored
|
||||
/// string is malformed (e.g. not in the expected two-part format, or not valid base64), or any other
|
||||
/// error occurs while verifying.
|
||||
/// </returns>
|
||||
public bool Verify(string password, string stored)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
namespace Infrastructure.PasswordHashing;
|
||||
|
||||
/// <summary>
|
||||
/// Service for hashing and verifying user passwords.
|
||||
/// </summary>
|
||||
public interface IPasswordInfrastructure
|
||||
{
|
||||
/// <summary>
|
||||
/// Hashes a plaintext password, generating a new random salt.
|
||||
/// </summary>
|
||||
/// <param name="password">The plaintext password to hash.</param>
|
||||
/// <returns>A string encoding both the salt and the resulting hash, suitable for storage.</returns>
|
||||
public string Hash(string password);
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a plaintext password against a previously stored hash.
|
||||
/// </summary>
|
||||
/// <param name="password">The plaintext password to verify.</param>
|
||||
/// <param name="stored">The stored salt/hash string previously produced by <see cref="Hash"/>.</param>
|
||||
/// <returns><c>true</c> if the password matches the stored hash; otherwise <c>false</c>.</returns>
|
||||
public bool Verify(string password, string stored);
|
||||
}
|
||||
|
||||
@@ -6,10 +6,34 @@ using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace Infrastructure.Repository.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IAuthRepository"/> backed by SQL Server stored procedures,
|
||||
/// handling user registration, credential lookup/rotation, and account verification.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">The factory used to create database connections.</param>
|
||||
public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<Domain.Entities.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>
|
||||
/// <param name="username">Unique username for the user</param>
|
||||
/// <param name="firstName">User's first name</param>
|
||||
/// <param name="lastName">User's last name</param>
|
||||
/// <param name="email">User's email address</param>
|
||||
/// <param name="dateOfBirth">User's date of birth</param>
|
||||
/// <param name="passwordHash">Hashed password</param>
|
||||
/// <returns>The newly created UserAccount with generated ID</returns>
|
||||
/// <exception cref="Exception">Thrown when the newly registered user cannot be retrieved after registration.</exception>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount> RegisterUserAsync(
|
||||
string username,
|
||||
string firstName,
|
||||
@@ -68,6 +92,13 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await GetUserByIdAsync(userAccountId) ?? throw new Exception("Failed to retrieve newly registered user.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by email address (typically used for login) using the
|
||||
/// <c>usp_GetUserAccountByEmail</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="email">Email address to search for</param>
|
||||
/// <returns>UserAccount if found, null otherwise</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetUserByEmailAsync(
|
||||
string email
|
||||
)
|
||||
@@ -83,6 +114,13 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by username (typically used for login) using the
|
||||
/// <c>usp_GetUserAccountByUsername</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="username">Username to search for</param>
|
||||
/// <returns>UserAccount if found, null otherwise</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetUserByUsernameAsync(
|
||||
string username
|
||||
)
|
||||
@@ -98,6 +136,13 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the active (non-revoked) credential for a user account using the
|
||||
/// <c>USP_GetActiveUserCredentialByUserAccountId</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="userAccountId">ID of the user account</param>
|
||||
/// <returns>Active UserCredential if found, null otherwise</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<UserCredential?> GetActiveCredentialByUserAccountIdAsync(
|
||||
Guid userAccountId
|
||||
)
|
||||
@@ -113,6 +158,13 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToCredentialEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <param name="userAccountId">ID of the user account</param>
|
||||
/// <param name="newPasswordHash">New hashed password</param>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task RotateCredentialAsync(
|
||||
Guid userAccountId,
|
||||
string newPasswordHash
|
||||
@@ -129,6 +181,12 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by ID using the <c>usp_GetUserAccountById</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="userAccountId">ID of the user account</param>
|
||||
/// <returns>UserAccount if found, null otherwise</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetUserByIdAsync(
|
||||
Guid userAccountId
|
||||
)
|
||||
@@ -144,6 +202,15 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <param name="userAccountId">ID of the user account to confirm</param>
|
||||
/// <returns>The confirmed <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if the user account does not exist.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails for a reason other than a duplicate verification record.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> ConfirmUserAccountAsync(
|
||||
Guid userAccountId
|
||||
)
|
||||
@@ -180,6 +247,13 @@ 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 for a matching record.
|
||||
/// </summary>
|
||||
/// <param name="userAccountId">ID of the user account</param>
|
||||
/// <returns>True if the user has a verification record, false otherwise</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<bool> IsUserVerifiedAsync(Guid userAccountId)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -194,6 +268,12 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
return result != null && result != DBNull.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a <see cref="SqlException"/> represents a duplicate key violation
|
||||
/// (SQL Server error 2601 or 2627), used to detect a concurrent duplicate verification insert.
|
||||
/// </summary>
|
||||
/// <param name="ex">The SQL exception to inspect.</param>
|
||||
/// <returns>True if the exception represents a duplicate key violation, false otherwise.</returns>
|
||||
private static bool IsDuplicateVerificationViolation(SqlException ex)
|
||||
{
|
||||
// 2601/2627 are duplicate key violations in SQL Server.
|
||||
@@ -204,6 +284,8 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
/// <summary>
|
||||
/// Maps a data reader row to a UserAccount entity.
|
||||
/// </summary>
|
||||
/// <param name="reader">The data reader positioned on the row to map.</param>
|
||||
/// <returns>The mapped <see cref="Domain.Entities.UserAccount"/> instance.</returns>
|
||||
protected override Domain.Entities.UserAccount MapToEntity(
|
||||
DbDataReader reader
|
||||
)
|
||||
@@ -227,8 +309,11 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a data reader row to a UserCredential entity.
|
||||
/// 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>
|
||||
/// <param name="reader">The data reader positioned on the row to map.</param>
|
||||
/// <returns>The mapped <see cref="UserCredential"/> instance.</returns>
|
||||
private static UserCredential MapToCredentialEntity(DbDataReader reader)
|
||||
{
|
||||
var entity = new UserCredential
|
||||
@@ -265,8 +350,12 @@ public class AuthRepository(ISqlConnectionFactory connectionFactory)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method to add a parameter to a database command.
|
||||
/// Helper method to add a parameter to a database command, converting <c>null</c> values to
|
||||
/// <see cref="DBNull.Value"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to add the parameter to.</param>
|
||||
/// <param name="name">The parameter name (including any prefix, e.g. "@Username").</param>
|
||||
/// <param name="value">The parameter value, or <c>null</c> to bind <see cref="DBNull.Value"/>.</param>
|
||||
private static void AddParameter(
|
||||
DbCommand command,
|
||||
string name,
|
||||
|
||||
@@ -65,8 +65,7 @@ public interface IAuthRepository
|
||||
/// Marks a user account as confirmed.
|
||||
/// </summary>
|
||||
/// <param name="userAccountId">ID of the user account to confirm</param>
|
||||
/// <returns>The confirmed UserAccount entity</returns>
|
||||
/// <exception cref="UnauthorizedException">If user account not found</exception>
|
||||
/// <returns>The confirmed UserAccount entity, or null if the user account does not exist</returns>
|
||||
Task<Domain.Entities.UserAccount?> ConfirmUserAccountAsync(Guid userAccountId);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -4,11 +4,22 @@ using Infrastructure.Repository.Sql;
|
||||
|
||||
namespace Infrastructure.Repository.Breweries;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IBreweryRepository"/> backed by SQL Server stored
|
||||
/// procedures.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">The factory used to create database connections.</param>
|
||||
public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<BreweryPost>(connectionFactory), IBreweryRepository
|
||||
{
|
||||
private readonly ISqlConnectionFactory _connectionFactory = connectionFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a brewery post by ID using the <c>USP_GetBreweryById</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post.</param>
|
||||
/// <returns>The matching <see cref="BreweryPost"/>, or <c>null</c> if not found.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<BreweryPost?> GetByIdAsync(Guid id)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -26,21 +37,44 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Not yet implemented.
|
||||
/// </summary>
|
||||
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
|
||||
/// <returns>Never returns; always throws.</returns>
|
||||
/// <exception cref="NotImplementedException">Always thrown.</exception>
|
||||
public Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Not yet implemented.
|
||||
/// </summary>
|
||||
/// <param name="brewery">The brewery post containing updated values.</param>
|
||||
/// <exception cref="NotImplementedException">Always thrown.</exception>
|
||||
public Task UpdateAsync(BreweryPost brewery)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Not yet implemented.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post to delete.</param>
|
||||
/// <exception cref="NotImplementedException">Always thrown.</exception>
|
||||
public Task DeleteAsync(Guid id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new brewery post and its location using the <c>USP_CreateBrewery</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="brewery">The brewery post to create. Must have a non-null <c>Location</c>.</param>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="brewery"/>.<c>Location</c> is <c>null</c>.</exception>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task CreateAsync(BreweryPost brewery)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -66,6 +100,13 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current row of a data reader to a <see cref="BreweryPost"/> entity, including its
|
||||
/// rowversion <c>Timer</c> field and, if location columns are present in the result set, its
|
||||
/// associated <see cref="BreweryPostLocation"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The data reader positioned on the row to map.</param>
|
||||
/// <returns>The mapped <see cref="BreweryPost"/> instance.</returns>
|
||||
protected override BreweryPost MapToEntity(DbDataReader reader)
|
||||
{
|
||||
var brewery = new BreweryPost();
|
||||
@@ -133,6 +174,13 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
return brewery;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method to add a parameter to a database command, converting <c>null</c> values to
|
||||
/// <see cref="DBNull.Value"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to add the parameter to.</param>
|
||||
/// <param name="name">The parameter name (including any prefix, e.g. "@BreweryName").</param>
|
||||
/// <param name="value">The parameter value, or <c>null</c> to bind <see cref="DBNull.Value"/>.</param>
|
||||
private static void AddParameter(
|
||||
DbCommand command,
|
||||
string name,
|
||||
|
||||
@@ -2,11 +2,42 @@ using Domain.Entities;
|
||||
|
||||
namespace Infrastructure.Repository.Breweries;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for CRUD operations on brewery post records.
|
||||
/// </summary>
|
||||
public interface IBreweryRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a brewery post by its unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post.</param>
|
||||
/// <returns>The matching <see cref="BreweryPost"/>, or <c>null</c> if not found.</returns>
|
||||
Task<BreweryPost?> GetByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all brewery posts, optionally paginated.
|
||||
/// </summary>
|
||||
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
|
||||
/// <returns>The collection of matching <see cref="BreweryPost"/> records.</returns>
|
||||
Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing brewery post.
|
||||
/// </summary>
|
||||
/// <param name="brewery">The brewery post containing updated values.</param>
|
||||
Task UpdateAsync(BreweryPost brewery);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a brewery post by its unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post to delete.</param>
|
||||
Task DeleteAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new brewery post, including its location details.
|
||||
/// </summary>
|
||||
/// <param name="brewery">The brewery post to create. Must have a non-null <c>Location</c>.</param>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="brewery"/> has no <c>Location</c>.</exception>
|
||||
Task CreateAsync(BreweryPost brewery);
|
||||
}
|
||||
@@ -3,9 +3,20 @@ using Infrastructure.Repository.Sql;
|
||||
|
||||
namespace Infrastructure.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for ADO.NET-based repositories, providing shared connection creation and
|
||||
/// entity-mapping infrastructure for derived repository implementations.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity type managed by the repository.</typeparam>
|
||||
/// <param name="connectionFactory">The factory used to create database connections.</param>
|
||||
public abstract class Repository<T>(ISqlConnectionFactory connectionFactory)
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates and opens a new database connection using the configured <see cref="ISqlConnectionFactory"/>.
|
||||
/// </summary>
|
||||
/// <returns>An open <see cref="DbConnection"/> ready for use.</returns>
|
||||
/// <exception cref="DbException">Thrown when the connection cannot be opened.</exception>
|
||||
protected async Task<DbConnection> CreateConnection()
|
||||
{
|
||||
var connection = connectionFactory.CreateConnection();
|
||||
@@ -13,5 +24,10 @@ public abstract class Repository<T>(ISqlConnectionFactory connectionFactory)
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current row of a data reader to an instance of <typeparamref name="T"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The data reader positioned on the row to map.</param>
|
||||
/// <returns>The mapped entity instance.</returns>
|
||||
protected abstract T MapToEntity(DbDataReader reader);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,11 @@ using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Infrastructure.Repository.Sql;
|
||||
|
||||
/// <summary>
|
||||
/// Default <see cref="ISqlConnectionFactory"/> implementation that creates SQL Server connections,
|
||||
/// resolving the connection string from environment variables or application configuration.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The application configuration, used as a fallback source for the connection string.</param>
|
||||
public class DefaultSqlConnectionFactory(IConfiguration configuration)
|
||||
: ISqlConnectionFactory
|
||||
{
|
||||
@@ -11,6 +16,17 @@ public class DefaultSqlConnectionFactory(IConfiguration configuration)
|
||||
configuration
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the SQL Server connection string, preferring (in order): the <c>DB_CONNECTION_STRING</c>
|
||||
/// environment variable, a connection string built from individual <c>DB_*</c> environment variables
|
||||
/// via <see cref="SqlConnectionStringHelper.BuildConnectionString"/>, and finally the <c>"Default"</c>
|
||||
/// connection string from <paramref name="configuration"/>.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The application configuration to fall back to.</param>
|
||||
/// <returns>The resolved SQL Server connection string.</returns>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Thrown when no connection string can be resolved from any of the supported sources.
|
||||
/// </exception>
|
||||
private static string GetConnectionString(IConfiguration configuration)
|
||||
{
|
||||
// Check for full connection string first
|
||||
@@ -42,6 +58,10 @@ public class DefaultSqlConnectionFactory(IConfiguration configuration)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new, unopened <see cref="SqlConnection"/> using the resolved connection string.
|
||||
/// </summary>
|
||||
/// <returns>A new <see cref="SqlConnection"/> instance.</returns>
|
||||
public DbConnection CreateConnection()
|
||||
{
|
||||
return new SqlConnection(_connectionString);
|
||||
|
||||
@@ -2,7 +2,14 @@ using System.Data.Common;
|
||||
|
||||
namespace Infrastructure.Repository.Sql;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating database connections used by repositories.
|
||||
/// </summary>
|
||||
public interface ISqlConnectionFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new, unopened database connection.
|
||||
/// </summary>
|
||||
/// <returns>A new <see cref="DbConnection"/> instance.</returns>
|
||||
DbConnection CreateConnection();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace Infrastructure.Repository.Sql;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for building SQL Server connection strings from environment variables.
|
||||
/// </summary>
|
||||
public static class SqlConnectionStringHelper
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -1,14 +1,51 @@
|
||||
namespace Infrastructure.Repository.UserAccount;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for CRUD operations on user account records.
|
||||
/// </summary>
|
||||
public interface IUserAccountRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a user account by its unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the user account.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
Task<Domain.Entities.UserAccount?> GetByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all user accounts, optionally paginated.
|
||||
/// </summary>
|
||||
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
|
||||
/// <returns>The collection of matching <see cref="Domain.Entities.UserAccount"/> records.</returns>
|
||||
Task<IEnumerable<Domain.Entities.UserAccount>> GetAllAsync(
|
||||
int? limit,
|
||||
int? offset
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing user account's details.
|
||||
/// </summary>
|
||||
/// <param name="userAccount">The user account containing updated values. Must have a valid <c>UserAccountId</c>.</param>
|
||||
Task UpdateAsync(Domain.Entities.UserAccount userAccount);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a user account by its unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the user account to delete.</param>
|
||||
Task DeleteAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by username.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to search for.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
Task<Domain.Entities.UserAccount?> GetByUsernameAsync(string username);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by email address.
|
||||
/// </summary>
|
||||
/// <param name="email">The email address to search for.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
Task<Domain.Entities.UserAccount?> GetByEmailAsync(string email);
|
||||
}
|
||||
|
||||
@@ -4,10 +4,21 @@ using Infrastructure.Repository.Sql;
|
||||
|
||||
namespace Infrastructure.Repository.UserAccount;
|
||||
|
||||
/// <summary>
|
||||
/// ADO.NET-based implementation of <see cref="IUserAccountRepository"/> backed by SQL Server
|
||||
/// stored procedures.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">The factory used to create database connections.</param>
|
||||
public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
: Repository<Domain.Entities.UserAccount>(connectionFactory),
|
||||
IUserAccountRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a user account by ID using the <c>usp_GetUserAccountById</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the user account.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetByIdAsync(Guid id)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -21,6 +32,15 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves all user accounts, optionally paginated, using 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>
|
||||
/// <param name="limit">The maximum number of records to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of records to skip, or <c>null</c> for no offset.</param>
|
||||
/// <returns>The collection of matching <see cref="Domain.Entities.UserAccount"/> records.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<IEnumerable<Domain.Entities.UserAccount>> GetAllAsync(
|
||||
int? limit,
|
||||
int? offset
|
||||
@@ -48,6 +68,12 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
return users;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <param name="userAccount">The user account containing updated values. Must have a valid <c>UserAccountId</c>.</param>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task UpdateAsync(Domain.Entities.UserAccount userAccount)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -65,6 +91,11 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a user account by ID using the <c>usp_DeleteUserAccount</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the user account to delete.</param>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task DeleteAsync(Guid id)
|
||||
{
|
||||
await using var connection = await CreateConnection();
|
||||
@@ -76,6 +107,12 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by username using the <c>usp_GetUserAccountByUsername</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to search for.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetByUsernameAsync(
|
||||
string username
|
||||
)
|
||||
@@ -91,6 +128,12 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a user account by email address using the <c>usp_GetUserAccountByEmail</c> stored procedure.
|
||||
/// </summary>
|
||||
/// <param name="email">The email address to search for.</param>
|
||||
/// <returns>The matching <see cref="Domain.Entities.UserAccount"/>, or <c>null</c> if not found.</returns>
|
||||
/// <exception cref="Microsoft.Data.SqlClient.SqlException">Thrown when the database command fails.</exception>
|
||||
public async Task<Domain.Entities.UserAccount?> GetByEmailAsync(
|
||||
string email
|
||||
)
|
||||
@@ -106,6 +149,11 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
return await reader.ReadAsync() ? MapToEntity(reader) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the current row of a data reader to a <see cref="Domain.Entities.UserAccount"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="reader">The data reader positioned on the row to map.</param>
|
||||
/// <returns>The mapped <see cref="Domain.Entities.UserAccount"/> instance.</returns>
|
||||
protected override Domain.Entities.UserAccount MapToEntity(
|
||||
DbDataReader reader
|
||||
)
|
||||
@@ -128,6 +176,13 @@ public class UserAccountRepository(ISqlConnectionFactory connectionFactory)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method to add a parameter to a database command, converting <c>null</c> values to
|
||||
/// <see cref="DBNull.Value"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to add the parameter to.</param>
|
||||
/// <param name="name">The parameter name (including any prefix, e.g. "@Username").</param>
|
||||
/// <param name="value">The parameter value, or <c>null</c> to bind <see cref="DBNull.Value"/>.</param>
|
||||
private static void AddParameter(
|
||||
DbCommand command,
|
||||
string name,
|
||||
|
||||
Reference in New Issue
Block a user