feat: MediaController

This commit is contained in:
2026-09-28 02:09:17 +04:00
parent afa993d76c
commit 5ca59a6ad8
6 changed files with 161 additions and 5 deletions
+24
View File
@@ -0,0 +1,24 @@
using System.Security.Claims;
namespace MemeVault.Api.Auth;
/// <summary>
/// Scoped-сервис: идентификатор аутентифицированного пользователя из JWT.
/// Доступен во всех контроллерах через DI.
/// </summary>
public sealed class CurrentUser(IHttpContextAccessor httpContextAccessor)
{
private ClaimsPrincipal Principal =>
httpContextAccessor.HttpContext?.User
?? throw new InvalidOperationException("No active HTTP context.");
public long TelegramId =>
long.Parse(Principal.FindFirstValue(ClaimTypes.NameIdentifier)
?? throw new InvalidOperationException("sub claim missing."));
public string? Username =>
Principal.FindFirstValue(ClaimTypes.Name);
public bool IsAuthenticated =>
Principal.Identity?.IsAuthenticated is true;
}
@@ -0,0 +1,54 @@
using MediatR;
using MemeVault.Api.Auth;
using MemeVault.Application.Commands.DeleteMedia;
using MemeVault.Application.Commands.UpdateMedia;
using MemeVault.Application.Queries.GetUserMedia;
using MemeVault.Application.Queries.SearchMedia;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MemeVault.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/[controller]")]
public sealed class MediaController(IMediator mediator, CurrentUser currentUser) : ControllerBase
{
// GET /api/media?q=...
[HttpGet]
public async Task<IActionResult> GetAll([FromQuery] string? q, CancellationToken ct)
{
var items = string.IsNullOrWhiteSpace(q)
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId), ct)
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q), ct);
return Ok(items);
}
// PATCH /api/media/{id}
[HttpPatch("{id:guid}")]
public async Task<IActionResult> Update(
Guid id,
[FromBody] UpdateMediaRequest request,
CancellationToken ct)
{
var ok = await mediator.Send(
new UpdateMediaCommand(id, currentUser.TelegramId, request.Caption, request.Tags),
ct);
return ok ? NoContent() : NotFound();
}
// DELETE /api/media/{id}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
await mediator.Send(new DeleteMediaCommand(id, currentUser.TelegramId), ct);
return NoContent();
}
}
public sealed record UpdateMediaRequest(
string? Caption,
IReadOnlyList<string> Tags
);
@@ -0,0 +1,31 @@
using MemeVault.Domain.Exceptions;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace MemeVault.Api.Middleware;
/// <summary>
/// Конвертирует DomainException в 400 Problem Details.
/// </summary>
public sealed class DomainExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext ctx,
Exception ex,
CancellationToken ct)
{
if (ex is not DomainException domain)
return false;
var problem = new ProblemDetails
{
Title = "Business rule violation",
Detail = domain.Message,
Status = StatusCodes.Status400BadRequest,
};
ctx.Response.StatusCode = problem.Status!.Value;
await ctx.Response.WriteAsJsonAsync(problem, ct);
return true;
}
}
+6 -5
View File
@@ -1,3 +1,4 @@
using MemeVault.Api.Middleware;
using MemeVault.Api.Auth;
using System.Text;
using MemeVault.Api.Options;
@@ -24,6 +25,8 @@ builder.Services.Configure<JwtOptions>(
builder.Services.AddSingleton<TelegramInitDataValidator>();
builder.Services.AddSingleton<JwtTokenService>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<CurrentUser>();
var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get<JwtOptions>()!;
@@ -45,6 +48,8 @@ builder.Services
};
});
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddAuthorization();
builder.Services.AddControllers();
@@ -53,16 +58,12 @@ builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpMetrics();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
// TODO: /api/media GET — список медиа пользователя
// TODO: /api/media/{id} PATCH — обновить caption / теги
// TODO: /api/media/{id} DELETE
// TODO: /api/tags GET — теги пользователя
// TODO: /api/collections GET/POST — коллекции
app.MapControllers();
app.MapMetrics();