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,15 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace API.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Custom ASP.NET Core authentication handler that validates bearer JWT access tokens
|
||||
/// supplied in the <c>Authorization</c> header against the <c>JWT</c> authentication scheme.
|
||||
/// </summary>
|
||||
/// <param name="options">The monitored options for the <c>JWT</c> authentication scheme.</param>
|
||||
/// <param name="logger">The logger factory used by the base <see cref="AuthenticationHandler{TOptions}"/>.</param>
|
||||
/// <param name="encoder">The URL encoder used by the base <see cref="AuthenticationHandler{TOptions}"/>.</param>
|
||||
/// <param name="tokenInfrastructure">The infrastructure service used to validate JWT access tokens.</param>
|
||||
/// <param name="configuration">The application configuration, used as a fallback source for the JWT secret key.</param>
|
||||
public class JwtAuthenticationHandler(
|
||||
IOptionsMonitor<JwtAuthenticationOptions> options,
|
||||
ILoggerFactory logger,
|
||||
@@ -16,6 +25,20 @@ public class JwtAuthenticationHandler(
|
||||
IConfiguration configuration
|
||||
) : AuthenticationHandler<JwtAuthenticationOptions>(options, logger, encoder)
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the incoming request's bearer JWT access token and produces an authentication result.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The signing secret is resolved first from the <c>ACCESS_TOKEN_SECRET</c> environment variable, falling
|
||||
/// back to the <c>Jwt:SecretKey</c> configuration value, to stay consistent with the secret source used
|
||||
/// when tokens are issued. Authentication fails if the secret is not configured, the
|
||||
/// <c>Authorization</c> header is missing, the header does not use the <c>Bearer</c> scheme, or the
|
||||
/// token fails validation.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A successful <see cref="AuthenticateResult"/> containing the validated <see cref="System.Security.Claims.ClaimsPrincipal"/>
|
||||
/// on success, or a failure result describing why authentication could not be completed.
|
||||
/// </returns>
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
// Use the same access-token secret source as TokenService to avoid mismatched validation.
|
||||
@@ -73,6 +96,11 @@ public class JwtAuthenticationHandler(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a JSON 401 Unauthorized response when authentication fails or is required but not supplied.
|
||||
/// </summary>
|
||||
/// <param name="properties">The authentication properties associated with the challenge.</param>
|
||||
/// <returns>A task that completes once the response body has been written.</returns>
|
||||
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.ContentType = "application/json";
|
||||
@@ -83,4 +111,8 @@ public class JwtAuthenticationHandler(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Options for the <c>JWT</c> authentication scheme handled by <see cref="JwtAuthenticationHandler"/>.
|
||||
/// </summary>
|
||||
/// <remarks>No additional options are defined beyond those provided by <see cref="AuthenticationSchemeOptions"/>.</remarks>
|
||||
public class JwtAuthenticationOptions : AuthenticationSchemeOptions { }
|
||||
|
||||
@@ -3,6 +3,13 @@ using Org.BouncyCastle.Asn1.Cms;
|
||||
|
||||
namespace API.Core.Contracts.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Payload returned to the client after a successful login or token refresh.
|
||||
/// </summary>
|
||||
/// <param name="UserAccountId">The unique identifier of the authenticated user account.</param>
|
||||
/// <param name="Username">The username of the authenticated user account.</param>
|
||||
/// <param name="RefreshToken">The newly issued refresh token used to obtain new access tokens.</param>
|
||||
/// <param name="AccessToken">The newly issued JWT access token used to authorize subsequent requests.</param>
|
||||
public record LoginPayload(
|
||||
Guid UserAccountId,
|
||||
string Username,
|
||||
@@ -10,6 +17,14 @@ public record LoginPayload(
|
||||
string AccessToken
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Payload returned to the client after a successful registration.
|
||||
/// </summary>
|
||||
/// <param name="UserAccountId">The unique identifier of the newly created user account.</param>
|
||||
/// <param name="Username">The username of the newly created user account.</param>
|
||||
/// <param name="RefreshToken">The refresh token issued for the new account.</param>
|
||||
/// <param name="AccessToken">The JWT access token issued for the new account.</param>
|
||||
/// <param name="ConfirmationEmailSent">Whether a confirmation email was successfully sent to the new user.</param>
|
||||
public record RegistrationPayload(
|
||||
Guid UserAccountId,
|
||||
string Username,
|
||||
@@ -18,4 +33,9 @@ public record RegistrationPayload(
|
||||
bool ConfirmationEmailSent
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Payload returned to the client after a user account's email has been confirmed.
|
||||
/// </summary>
|
||||
/// <param name="UserAccountId">The unique identifier of the user account that was confirmed.</param>
|
||||
/// <param name="ConfirmedDate">The date and time at which the account was confirmed.</param>
|
||||
public record ConfirmationPayload(Guid UserAccountId, DateTime ConfirmedDate);
|
||||
|
||||
@@ -3,14 +3,31 @@ using FluentValidation;
|
||||
|
||||
namespace API.Core.Contracts.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Request body for the login endpoint, containing the credentials used to authenticate a user.
|
||||
/// </summary>
|
||||
public record LoginRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// The username of the account attempting to log in.
|
||||
/// </summary>
|
||||
public string Username { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// The plaintext password of the account attempting to log in.
|
||||
/// </summary>
|
||||
public string Password { get; init; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates <see cref="LoginRequest"/> instances before they are processed by the login endpoint.
|
||||
/// </summary>
|
||||
public class LoginRequestValidator : AbstractValidator<LoginRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures validation rules requiring both <see cref="LoginRequest.Username"/> and
|
||||
/// <see cref="LoginRequest.Password"/> to be non-empty.
|
||||
/// </summary>
|
||||
public LoginRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Username).NotEmpty().WithMessage("Username is required");
|
||||
|
||||
@@ -2,14 +2,26 @@ using FluentValidation;
|
||||
|
||||
namespace API.Core.Contracts.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Request body for the token refresh endpoint, containing the refresh token used to obtain a new access token.
|
||||
/// </summary>
|
||||
public record RefreshTokenRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// The refresh token previously issued to the client during login, registration, or a prior refresh.
|
||||
/// </summary>
|
||||
public string RefreshToken { get; init; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates <see cref="RefreshTokenRequest"/> instances before they are processed by the refresh endpoint.
|
||||
/// </summary>
|
||||
public class RefreshTokenRequestValidator
|
||||
: AbstractValidator<RefreshTokenRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures a validation rule requiring <see cref="RefreshTokenRequest.RefreshToken"/> to be non-empty.
|
||||
/// </summary>
|
||||
public RefreshTokenRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.RefreshToken)
|
||||
|
||||
@@ -3,6 +3,15 @@ using FluentValidation;
|
||||
|
||||
namespace API.Core.Contracts.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Request body for the registration endpoint, containing the details needed to create a new user account.
|
||||
/// </summary>
|
||||
/// <param name="Username">The desired username; must be 3-64 characters and contain only letters, numbers, dots, underscores, and hyphens.</param>
|
||||
/// <param name="FirstName">The user's first name; up to 128 characters.</param>
|
||||
/// <param name="LastName">The user's last name; up to 128 characters.</param>
|
||||
/// <param name="Email">The user's email address; up to 128 characters and must be a valid email format.</param>
|
||||
/// <param name="DateOfBirth">The user's date of birth; the user must be at least 19 years old.</param>
|
||||
/// <param name="Password">The desired plaintext password; must be at least 8 characters and contain an uppercase letter, a lowercase letter, a number, and a special character.</param>
|
||||
public record RegisterRequest(
|
||||
string Username,
|
||||
string FirstName,
|
||||
@@ -12,8 +21,15 @@ public record RegisterRequest(
|
||||
string Password
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Validates <see cref="RegisterRequest"/> instances before they are processed by the registration endpoint.
|
||||
/// </summary>
|
||||
public class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures validation rules for username format and length, first/last name length, email format and
|
||||
/// length, minimum age based on date of birth, and password strength requirements.
|
||||
/// </summary>
|
||||
public RegisterRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Username)
|
||||
|
||||
@@ -2,8 +2,17 @@ using FluentValidation;
|
||||
|
||||
namespace API.Core.Contracts.Breweries;
|
||||
|
||||
/// <summary>
|
||||
/// Validates <see cref="BreweryCreateDto"/> instances before they are processed by the brewery creation endpoint.
|
||||
/// </summary>
|
||||
public class BreweryCreateDtoValidator : AbstractValidator<BreweryCreateDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures validation rules requiring <see cref="BreweryCreateDto.PostedById"/>,
|
||||
/// <see cref="BreweryCreateDto.BreweryName"/>, <see cref="BreweryCreateDto.Description"/>, and
|
||||
/// <see cref="BreweryCreateDto.Location"/> to be present, with length limits on the name, description,
|
||||
/// address line 1, and postal code fields.
|
||||
/// </summary>
|
||||
public BreweryCreateDtoValidator()
|
||||
{
|
||||
RuleFor(x => x.PostedById)
|
||||
|
||||
@@ -1,41 +1,147 @@
|
||||
namespace API.Core.Contracts.Breweries;
|
||||
|
||||
/// <summary>
|
||||
/// Request payload describing the location of a brewery to be created, supplied as part of
|
||||
/// <see cref="BreweryCreateDto"/>.
|
||||
/// </summary>
|
||||
public class BreweryLocationCreateDto
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the city in which the brewery is located.
|
||||
/// </summary>
|
||||
public Guid CityId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The primary street address line of the brewery.
|
||||
/// </summary>
|
||||
public string AddressLine1 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// An optional secondary address line (e.g. suite or unit number).
|
||||
/// </summary>
|
||||
public string? AddressLine2 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The postal/ZIP code of the brewery's address.
|
||||
/// </summary>
|
||||
public string PostalCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The optional geographic coordinates of the brewery, in a raw binary representation.
|
||||
/// </summary>
|
||||
public byte[]? Coordinates { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents the location details of an existing brewery, as returned in <see cref="BreweryDto"/>.
|
||||
/// </summary>
|
||||
public class BreweryLocationDto
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the brewery's location record.
|
||||
/// </summary>
|
||||
public Guid BreweryPostLocationId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The unique identifier of the brewery post that this location belongs to.
|
||||
/// </summary>
|
||||
public Guid BreweryPostId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The unique identifier of the city in which the brewery is located.
|
||||
/// </summary>
|
||||
public Guid CityId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The primary street address line of the brewery.
|
||||
/// </summary>
|
||||
public string AddressLine1 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// An optional secondary address line (e.g. suite or unit number).
|
||||
/// </summary>
|
||||
public string? AddressLine2 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The postal/ZIP code of the brewery's address.
|
||||
/// </summary>
|
||||
public string PostalCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The optional geographic coordinates of the brewery, in a raw binary representation.
|
||||
/// </summary>
|
||||
public byte[]? Coordinates { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request body used by <see cref="Controllers.BreweryController.Create"/> to create a new brewery post.
|
||||
/// </summary>
|
||||
public class BreweryCreateDto
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the user account that is creating the brewery post.
|
||||
/// </summary>
|
||||
public Guid PostedById { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The name of the brewery; required and limited to 256 characters.
|
||||
/// </summary>
|
||||
public string BreweryName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// A description of the brewery; required and limited to 512 characters.
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The location details of the brewery being created.
|
||||
/// </summary>
|
||||
public BreweryLocationCreateDto Location { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a brewery post as returned by, or submitted to, the brewery endpoints, including its
|
||||
/// metadata and optional location.
|
||||
/// </summary>
|
||||
public class BreweryDto
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the brewery post.
|
||||
/// </summary>
|
||||
public Guid BreweryPostId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The unique identifier of the user account that created the brewery post.
|
||||
/// </summary>
|
||||
public Guid PostedById { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The name of the brewery.
|
||||
/// </summary>
|
||||
public string BreweryName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// A description of the brewery.
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The date and time at which the brewery post was created.
|
||||
/// </summary>
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The date and time at which the brewery post was last updated, or <c>null</c> if it has never been updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A row-version/concurrency token used to detect conflicting concurrent updates to the brewery post.
|
||||
/// </summary>
|
||||
public byte[]? Timer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The location details of the brewery, or <c>null</c> if no location is associated with it.
|
||||
/// </summary>
|
||||
public BreweryLocationDto? Location { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
namespace API.Core.Contracts.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Generic envelope used to wrap API responses that carry a data payload alongside a human-readable message.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the data payload returned in the response.</typeparam>
|
||||
public record ResponseBody<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// A human-readable message describing the outcome of the request.
|
||||
/// </summary>
|
||||
public required string Message { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The data payload associated with the response.
|
||||
/// </summary>
|
||||
public required T Payload { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Envelope used to wrap API responses that carry only a human-readable message and no data payload.
|
||||
/// </summary>
|
||||
public record ResponseBody
|
||||
{
|
||||
/// <summary>
|
||||
/// A human-readable message describing the outcome of the request.
|
||||
/// </summary>
|
||||
public required string Message { get; init; }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,17 @@ using Service.Auth;
|
||||
|
||||
namespace API.Core.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles user authentication concerns: registration, login, email confirmation, and token refresh.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The controller is decorated with <c>[Authorize(AuthenticationSchemes = "JWT")]</c> by default, but most
|
||||
/// actions opt out via <c>[AllowAnonymous]</c> since they are entry points used before a caller holds a token.
|
||||
/// </remarks>
|
||||
/// <param name="registerService">Service used to register new user accounts.</param>
|
||||
/// <param name="loginService">Service used to authenticate existing user accounts.</param>
|
||||
/// <param name="confirmationService">Service used to confirm user accounts and resend confirmation emails.</param>
|
||||
/// <param name="tokenService">Service used to refresh JWT access/refresh token pairs.</param>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize(AuthenticationSchemes = "JWT")]
|
||||
@@ -17,6 +28,15 @@ namespace API.Core.Controllers
|
||||
ITokenService tokenService
|
||||
) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers a new user account.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Allows anonymous access. On success, responds with <c>201 Created</c> containing the new user's ID,
|
||||
/// username, issued refresh/access tokens, and whether a confirmation email was sent.
|
||||
/// </remarks>
|
||||
/// <param name="req">The registration details, including username, name, email, date of birth, and password.</param>
|
||||
/// <returns>A <c>201 Created</c> result wrapping a <see cref="ResponseBody{T}"/> of <see cref="RegistrationPayload"/>.</returns>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("register")]
|
||||
public async Task<ActionResult<UserAccount>> Register(
|
||||
@@ -50,6 +70,15 @@ namespace API.Core.Controllers
|
||||
return Created("/", response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates a user with a username and password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Allows anonymous access. On success, responds with <c>200 OK</c> containing the user's ID,
|
||||
/// username, and a newly issued refresh/access token pair.
|
||||
/// </remarks>
|
||||
/// <param name="req">The login credentials (username and password).</param>
|
||||
/// <returns>An <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of <see cref="LoginPayload"/>.</returns>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult> Login([FromBody] LoginRequest req)
|
||||
@@ -70,6 +99,15 @@ namespace API.Core.Controllers
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms a user account using a confirmation token.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Requires JWT authentication. On success, responds with <c>200 OK</c> containing the confirmed
|
||||
/// user's ID and the confirmation timestamp.
|
||||
/// </remarks>
|
||||
/// <param name="token">The confirmation token supplied via the confirmation email link.</param>
|
||||
/// <returns>A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of <see cref="ConfirmationPayload"/>.</returns>
|
||||
[HttpPost("confirm")]
|
||||
public async Task<ActionResult> Confirm([FromQuery] string token)
|
||||
{
|
||||
@@ -86,6 +124,14 @@ namespace API.Core.Controllers
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resends the account confirmation email for the specified user.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Requires JWT authentication. On success, responds with <c>200 OK</c>.
|
||||
/// </remarks>
|
||||
/// <param name="userId">The unique identifier of the user account to resend the confirmation email for.</param>
|
||||
/// <returns>A <c>200 OK</c> result wrapping a <see cref="ResponseBody"/> confirming the email was resent.</returns>
|
||||
[HttpPost("confirm/resend")]
|
||||
public async Task<ActionResult> ResendConfirmation([FromQuery] Guid userId)
|
||||
{
|
||||
@@ -93,6 +139,15 @@ namespace API.Core.Controllers
|
||||
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>
|
||||
/// Allows anonymous access. On success, responds with <c>200 OK</c> containing the user's ID,
|
||||
/// username, and the newly issued refresh/access token pair.
|
||||
/// </remarks>
|
||||
/// <param name="req">The request containing the refresh token to exchange.</param>
|
||||
/// <returns>A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of <see cref="LoginPayload"/>.</returns>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("refresh")]
|
||||
public async Task<ActionResult> Refresh(
|
||||
|
||||
@@ -1,16 +1,34 @@
|
||||
using API.Core.Contracts.Breweries;
|
||||
using API.Core.Contracts.Common;
|
||||
using Domain.Entities;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Service.Breweries;
|
||||
|
||||
namespace API.Core.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Provides CRUD endpoints for managing brewery posts.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The controller is decorated with <c>[Authorize(AuthenticationSchemes = "JWT")]</c> by default; read endpoints
|
||||
/// (<see cref="GetById"/> and <see cref="GetAll"/>) opt out via <c>[AllowAnonymous]</c>.
|
||||
/// </remarks>
|
||||
/// <param name="breweryService">Service used to query and mutate brewery post data.</param>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize(AuthenticationSchemes = "JWT")]
|
||||
public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a single brewery post by its unique identifier.
|
||||
/// </summary>
|
||||
/// <remarks>Allows anonymous access.</remarks>
|
||||
/// <param name="id">The unique identifier of the brewery post to retrieve.</param>
|
||||
/// <returns>
|
||||
/// A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of <see cref="BreweryDto"/> if found;
|
||||
/// otherwise a <c>404 Not Found</c> result wrapping a <see cref="ResponseBody"/> error message.
|
||||
/// </returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<ResponseBody<BreweryDto>>> GetById(Guid id)
|
||||
@@ -26,6 +44,13 @@ public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a paginated list of brewery posts.
|
||||
/// </summary>
|
||||
/// <remarks>Allows anonymous access.</remarks>
|
||||
/// <param name="limit">The maximum number of brewery posts to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of brewery posts to skip before returning results, or <c>null</c> for no offset.</param>
|
||||
/// <returns>A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of a collection of <see cref="BreweryDto"/>.</returns>
|
||||
[AllowAnonymous]
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<ResponseBody<IEnumerable<BreweryDto>>>> GetAll(
|
||||
@@ -40,6 +65,14 @@ public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new brewery post.
|
||||
/// </summary>
|
||||
/// <param name="dto">The brewery details to create, including the posting user, name, description, and location.</param>
|
||||
/// <returns>
|
||||
/// A <c>201 Created</c> result wrapping a <see cref="ResponseBody{T}"/> of the newly created <see cref="BreweryDto"/>
|
||||
/// if creation succeeds; otherwise a <c>400 Bad Request</c> result wrapping a <see cref="ResponseBody"/> error message.
|
||||
/// </returns>
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ResponseBody<BreweryDto>>> Create([FromBody] BreweryCreateDto dto)
|
||||
{
|
||||
@@ -67,6 +100,16 @@ public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing brewery post.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post from the route, which must match <paramref name="dto"/>'s ID.</param>
|
||||
/// <param name="dto">The updated brewery details, including the posting user, name, description, and optional location.</param>
|
||||
/// <returns>
|
||||
/// A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> of the updated brewery (as a <see cref="BreweryPost"/>)
|
||||
/// if the update succeeds; otherwise a <c>400 Bad Request</c> result wrapping a <see cref="ResponseBody"/> error message
|
||||
/// (returned when the route ID does not match the payload ID, or when the update itself fails).
|
||||
/// </returns>
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<ActionResult<ResponseBody<BreweryDto>>> Update(Guid id, [FromBody] BreweryDto dto)
|
||||
{
|
||||
@@ -92,13 +135,18 @@ public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
if (!result.Success)
|
||||
return BadRequest(new ResponseBody { Message = result.Message });
|
||||
|
||||
return Ok(new ResponseBody<BreweryDto>
|
||||
return Ok(new ResponseBody<BreweryPost>
|
||||
{
|
||||
Message = "Brewery updated successfully.",
|
||||
Payload = MapToDto(result.Brewery),
|
||||
Payload = result.Brewery,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a brewery post.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the brewery post to delete.</param>
|
||||
/// <returns>A <c>200 OK</c> result wrapping a <see cref="ResponseBody"/> confirming the deletion.</returns>
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<ActionResult<ResponseBody>> Delete(Guid id)
|
||||
{
|
||||
@@ -106,7 +154,13 @@ public class BreweryController(IBreweryService breweryService) : ControllerBase
|
||||
return Ok(new ResponseBody { Message = "Brewery deleted successfully." });
|
||||
}
|
||||
|
||||
private static BreweryDto MapToDto(Domain.Entities.BreweryPost b) => new()
|
||||
/// <summary>
|
||||
/// Maps a <see cref="BreweryPost"/> domain entity to its <see cref="BreweryDto"/> representation,
|
||||
/// including its location, if present.
|
||||
/// </summary>
|
||||
/// <param name="b">The brewery post entity to map.</param>
|
||||
/// <returns>The mapped <see cref="BreweryDto"/>.</returns>
|
||||
private static BreweryDto MapToDto(BreweryPost b) => new()
|
||||
{
|
||||
BreweryPostId = b.BreweryPostId,
|
||||
PostedById = b.PostedById,
|
||||
|
||||
@@ -2,11 +2,22 @@ using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace API.Core.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles requests that do not match any other route, used as the application's fallback controller.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Excluded from API explorer/Swagger output via <c>[ApiExplorerSettings(IgnoreApi = true)]</c>.
|
||||
/// Wired up as the fallback target via <c>app.MapFallbackToController("Handle404", "NotFound")</c> in <c>Program.cs</c>.
|
||||
/// </remarks>
|
||||
[ApiController]
|
||||
[ApiExplorerSettings(IgnoreApi = true)]
|
||||
[Route("error")] // required
|
||||
public class NotFoundController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a generic 404 response for any request that did not match a defined route.
|
||||
/// </summary>
|
||||
/// <returns>A <c>404 Not Found</c> result with a JSON body containing a "Route not found." message.</returns>
|
||||
[HttpGet("404")] //required
|
||||
public IActionResult Handle404()
|
||||
{
|
||||
|
||||
@@ -5,11 +5,22 @@ using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace API.Core.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Sample controller demonstrating an endpoint that requires JWT authentication.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize(AuthenticationSchemes = "JWT")]
|
||||
public class ProtectedController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the authenticated caller's user ID and username, extracted from the JWT claims.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <c>200 OK</c> result wrapping a <see cref="ResponseBody{T}"/> whose payload contains the
|
||||
/// caller's <c>userId</c> (from <see cref="ClaimTypes.NameIdentifier"/>) and <c>username</c>
|
||||
/// (from <see cref="ClaimTypes.Name"/>), either of which may be <c>null</c> if not present in the token.
|
||||
/// </returns>
|
||||
[HttpGet]
|
||||
public ActionResult<ResponseBody<object>> Get()
|
||||
{
|
||||
|
||||
@@ -4,10 +4,20 @@ using Service.UserManagement.User;
|
||||
|
||||
namespace API.Core.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides read-only endpoints for retrieving user accounts.
|
||||
/// </summary>
|
||||
/// <param name="userService">Service used to query user account data.</param>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class UserController(IUserService userService) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves a paginated list of user accounts.
|
||||
/// </summary>
|
||||
/// <param name="limit">The maximum number of user accounts to return, or <c>null</c> for no limit.</param>
|
||||
/// <param name="offset">The number of user accounts to skip before returning results, or <c>null</c> for no offset.</param>
|
||||
/// <returns>A <c>200 OK</c> result containing the collection of <see cref="UserAccount"/> entities.</returns>
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<UserAccount>>> GetAll(
|
||||
[FromQuery] int? limit,
|
||||
@@ -18,6 +28,11 @@ namespace API.Core.Controllers
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a single user account by its unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the user account to retrieve.</param>
|
||||
/// <returns>A <c>200 OK</c> result containing the matching <see cref="UserAccount"/>.</returns>
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<UserAccount>> GetById(Guid id)
|
||||
{
|
||||
|
||||
@@ -9,9 +9,32 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace API.Core;
|
||||
|
||||
/// <summary>
|
||||
/// MVC exception filter that converts unhandled exceptions raised by controller actions into
|
||||
/// consistent JSON error responses with appropriate HTTP status codes.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger used to record unhandled exceptions before they are translated into a response.</param>
|
||||
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
|
||||
: IExceptionFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// Logs the exception and sets <see cref="ExceptionContext.Result"/> to an appropriate error response,
|
||||
/// marking the exception as handled.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Maps exception types to responses as follows:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><see cref="FluentValidation.ValidationException"/> → <c>400 Bad Request</c> with per-property validation error messages.</description></item>
|
||||
/// <item><description><see cref="ConflictException"/> → <c>409 Conflict</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||
/// <item><description><see cref="NotFoundException"/> → <c>404 Not Found</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||
/// <item><description><see cref="UnauthorizedException"/> → <c>401 Unauthorized</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||
/// <item><description><see cref="ForbiddenException"/> → <c>403 Forbidden</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||
/// <item><description><see cref="SqlException"/> → <c>503 Service Unavailable</c> with a generic database error message.</description></item>
|
||||
/// <item><description><see cref="Domain.Exceptions.ValidationException"/> → <c>400 Bad Request</c> with a <see cref="ResponseBody"/> message.</description></item>
|
||||
/// <item><description>Any other exception → <c>500 Internal Server Error</c> with a generic error message.</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
/// <param name="context">The context for the unhandled exception, including the exception itself and the result to populate.</param>
|
||||
public void OnException(ExceptionContext context)
|
||||
{
|
||||
logger.LogError(context.Exception, "Unhandled exception occurred");
|
||||
|
||||
Reference in New Issue
Block a user