H2: Hero-module (tabellen en migratie, beheer-API, publieke GET /hero, afbeeldingsupload met focus, opschoonservice, teksten) en OpenAPI-snapshot

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 15:46:55 +01:00
co-authored by Claude Sonnet 5.5
parent 43925cbf37
commit ae04120d8c
31 changed files with 4221 additions and 3 deletions
@@ -0,0 +1,156 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Availability;
using SlpModularCms.Core.Media;
using SlpModularCms.Core.Texts;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Modules.Hero.Controllers;
/// <summary>
/// The hero of the site. <c>GET /hero</c> is what websites read (200 with the hero, 204 when there is none to show);
/// management (<c>GET /hero/all</c>, <c>PUT /hero</c>) is for administrators.
/// </summary>
[ApiController]
[Route("hero")]
public class HeroController(IHeroService service, IPublicHeroService publicService) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting("hero-public")]
[ProducesResponseType<PublicHeroDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
Response.Headers.CacheControl = "public, max-age=60";
var hero = await publicService.GetActiveAsync(cancellationToken);
return hero is null ? NoContent() : Ok(hero);
}
[HttpGet("all")]
[Authorize(Policy = "AdminOnly")]
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
public async Task<IActionResult> GetForAdmin(CancellationToken cancellationToken)
=> Ok(await service.GetAsync(cancellationToken));
[HttpPut]
[Authorize(Policy = "AdminOnly")]
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Save([FromBody] HeroSaveRequest request, CancellationToken cancellationToken)
{
try
{
return Ok(await service.SaveAsync(request, HeroCaller.Id(User), cancellationToken));
}
catch (HeroSaveRejectedException exception)
{
ModelState.AddModelError(exception.Field, exception.Message);
return ValidationProblem(ModelState);
}
}
}
/// <summary>Images of the hero: upload, focus and delete. Administrators only.</summary>
[ApiController]
[Route("hero/images")]
[Authorize(Policy = "AdminOnly")]
public class HeroImagesController(IHeroImageService service, IOptions<MediaOptions> media) : ControllerBase
{
/// <summary>The body limit leaves room for the multipart envelope around the file limit of <see cref="MediaOptions.MaxUploadBytes"/>.</summary>
private const long RequestLimit = 12 * 1024 * 1024;
[HttpPost]
[RequestSizeLimit(RequestLimit)]
[EnableRateLimiting("hero-upload")]
[Consumes("multipart/form-data")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status201Created)]
public async Task<IActionResult> Upload(IFormFile file, CancellationToken cancellationToken)
{
try
{
await using var stream = file.OpenReadStream();
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken);
return Created($"/api/v1/hero/images/{image.Id}", image);
}
catch (ImageRejectedException rejection)
{
return Rejected(rejection);
}
catch (MediaStorageFullException)
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "storage_full", message = Texts().Get(HeroTexts.Image.StorageFull) });
}
}
[HttpPut("{id:guid}/focus")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
{
try
{
return Ok(await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken));
}
catch (HeroImageNotFoundException)
{
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
}
catch (ImageRejectedException rejection)
{
return Rejected(rejection);
}
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
{
try
{
await service.DeleteAsync(id, HeroCaller.Id(User), cancellationToken);
return NoContent();
}
catch (HeroImageNotFoundException)
{
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
}
catch (HeroImageInUseException)
{
return Conflict(new { error = "in_use", message = Texts().Get(HeroTexts.Image.InUse) });
}
}
private ITextCatalog Texts() => HttpTexts.From(HttpContext);
private IActionResult Rejected(ImageRejectedException rejection)
{
var status = rejection.Reason switch
{
ImageRejection.TooLarge => StatusCodes.Status413PayloadTooLarge,
ImageRejection.Busy => StatusCodes.Status429TooManyRequests,
ImageRejection.Unavailable => StatusCodes.Status503ServiceUnavailable,
_ => StatusCodes.Status400BadRequest,
};
var key = HeroTexts.Image.For(rejection.Reason);
var message = rejection.Reason == ImageRejection.TooLarge
? Texts().Get(key, args: ("max", media.Value.MaxUploadBytes / (1024 * 1024)))
: Texts().Get(key);
return StatusCode(status, new { error = rejection.Code, message });
}
}
internal static class HeroCaller
{
public static Guid Id(ClaimsPrincipal user)
{
var claim = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
}