Základní backend: migrace, autentizace JWT, role, Swagger

- Helpdesk.Migrator (DbUp) aplikuje db/migrations, evidence v schema_version
- Domain/Application/Infrastructure/Api podle Clean Architecture
- registrace, ověření e-mailu, login, refresh s rotací, logout, reset hesla
- JWT podle RFC 7519 evidované jen podle jti v auth_token
- správa uživatelů a rolí, číselníky, ProblemDetails, Swagger UI
- Docker Compose (db, migrator, api), oddělené DB účty
- notifikace mají cizí klíče na issue a proposal
- unit testy domény a zabezpečení

Closes #1, closes #2, closes #3, closes #4, closes #5, closes #9
This commit is contained in:
PatTheEvil committed 2026-10-28 21:43:17 +01:00
1 parent fc76be7d69
commit a51d386278
64 files changed
+4394 -1

No files matched your search

@@ -0,0 +1,41 @@
using FluentValidation;
using Helpdesk.Application.Common;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Infrastructure;
/// <summary>Převod výjimek na ProblemDetails (RFC 9457): aplikační chyby → 4xx, validace → 400 se seznamem chyb.</summary>
internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
ProblemDetails? problem = exception switch
{
ValidationException validation => new ValidationProblemDetails(
validation.Errors
.GroupBy(e => JsonName(e.PropertyName))
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray()))
{
Status = StatusCodes.Status400BadRequest,
Title = "Neplatná vstupní data.",
},
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
_ => null,
};
if (problem is null)
return false; // neočekávaná chyba → výchozí 500 bez detailů
httpContext.Response.StatusCode = problem.Status!.Value;
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = problem,
Exception = exception,
});
}
private static string JsonName(string propertyName) =>
string.IsNullOrEmpty(propertyName) ? propertyName : char.ToLowerInvariant(propertyName[0]) + propertyName[1..];
}
@@ -0,0 +1,45 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Helpdesk.Api.Infrastructure;
public static class AuthenticationSetup
{
/// <summary>
/// Ověření access tokenu podle RFC 7519, kap. 7.2 (kap. 10.1 návrhu):
/// body 1–4 (podpis HS256, <c>typ</c> = <c>at+jwt</c>, <c>iss</c>/<c>aud</c>, <c>exp</c>) zajistí JwtBearer,
/// bod 5 (zneplatněné <c>jti</c>) kontroluje <see cref="JwtBearerEvents.OnTokenValidated"/>.
/// </summary>
public static IServiceCollection AddHelpdeskAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var jwt = configuration.GetSection(JwtOptions.Section).Get<JwtOptions>() ?? new JwtOptions();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false; // claimy zůstanou jako "sub", "role", "jti"
options.TokenValidationParameters = JwtTokenService.CreateValidationParameters(jwt, TokenType.Access);
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var store = context.HttpContext.RequestServices.GetRequiredService<IRevokedTokenStore>();
if (context.SecurityToken is not JsonWebToken token || string.IsNullOrEmpty(token.Id) || store.IsRevoked(token.Id))
context.Fail("Token byl zneplatněn.");
return Task.CompletedTask;
},
};
});
return services;
}
}
public static class RateLimitPolicies
{
public const string Auth = "auth";
}
@@ -0,0 +1,16 @@
using Helpdesk.Application.Abstractions;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Helpdesk.Api.Infrastructure;
/// <summary>Přihlášený uživatel z claimů ověřeného access tokenu.</summary>
internal sealed class HttpCurrentUser(IHttpContextAccessor accessor) : ICurrentUser
{
public int Id => int.Parse(Claim(JwtRegisteredClaimNames.Sub));
public string TokenId => Claim(JwtRegisteredClaimNames.Jti);
private string Claim(string type) =>
accessor.HttpContext?.User.FindFirst(type)?.Value
?? throw new InvalidOperationException($"Požadavek nemá claim '{type}' – endpoint musí vyžadovat přihlášení.");
}
@@ -0,0 +1,11 @@
namespace Helpdesk.Api.Infrastructure;
/// <summary>Kódy rolí z claimu <c>role</c> pro <c>[Authorize(Roles = …)]</c>; odpovídají <c>UserRole.ToCode()</c>.</summary>
public static class Roles
{
public const string Student = "STUDENT";
public const string Teacher = "TEACHER";
public const string FacilityManager = "FACILITY_MANAGER";
public const string Management = "MANAGEMENT";
public const string Admin = "ADMIN";
}
@@ -0,0 +1,40 @@
using Microsoft.OpenApi;
namespace Helpdesk.Api.Infrastructure;
public static class SwaggerSetup
{
private const string SchemeId = "Bearer";
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
{
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Univerzitní helpdesk – API",
Version = "v1",
Description = "REST API pro webovou a mobilní aplikaci. Access token získáte přes POST /api/auth/login.",
});
options.AddSecurityDefinition(SchemeId, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Vložte access token (bez předpony „Bearer“).",
});
options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
});
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
if (File.Exists(xml))
options.IncludeXmlComments(xml);
});
return services;
}
}