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

+10
View File
@@ -0,0 +1,10 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
</Project>
+27
View File
@@ -0,0 +1,27 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<!-- Pomelo zatím nemá verzi pro EF Core 10 – EF Core 9 běží na .NET 10 bez omezení. -->
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.22" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.22" />
<PackageVersion Include="Pomelo.EntityFrameworkCore.MySql" Version="9.0.0" />
<PackageVersion Include="EFCore.NamingConventions" Version="9.0.0" />
<PackageVersion Include="dbup-mysql" Version="6.1.0" />
<!-- Pomelo a DbUp tahají MySqlConnector se známou zranitelností (GHSA-473q-m89c-ghf8) – připnutá opravená verze. -->
<PackageVersion Include="MySqlConnector" Version="2.6.2" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageVersion Include="FluentValidation" Version="12.2.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<!-- testy -->
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup>
</Project>
+35
View File
@@ -0,0 +1,35 @@
# Vícefázový build backendu. Kontext sestavení = kořen repozitáře (kvůli db/migrations).
# docker build -f backend/Dockerfile --target api .
# docker build -f backend/Dockerfile --target migrator .
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
# Nejdřív jen projektové soubory – restore balíčků se pak cachuje, dokud se nezmění závislosti.
COPY backend/Directory.Build.props backend/Directory.Packages.props ./
COPY backend/src/Helpdesk.Domain/Helpdesk.Domain.csproj src/Helpdesk.Domain/
COPY backend/src/Helpdesk.Application/Helpdesk.Application.csproj src/Helpdesk.Application/
COPY backend/src/Helpdesk.Infrastructure/Helpdesk.Infrastructure.csproj src/Helpdesk.Infrastructure/
COPY backend/src/Helpdesk.Api/Helpdesk.Api.csproj src/Helpdesk.Api/
COPY backend/src/Helpdesk.Migrator/Helpdesk.Migrator.csproj src/Helpdesk.Migrator/
RUN dotnet restore src/Helpdesk.Api/Helpdesk.Api.csproj \
&& dotnet restore src/Helpdesk.Migrator/Helpdesk.Migrator.csproj
COPY backend/src/ src/
RUN dotnet publish src/Helpdesk.Api/Helpdesk.Api.csproj -c Release -o /out/api --no-restore \
&& dotnet publish src/Helpdesk.Migrator/Helpdesk.Migrator.csproj -c Release -o /out/migrator --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS api
WORKDIR /app
COPY --from=build /out/api .
RUN mkdir -p /app/uploads && chown "$APP_UID" /app/uploads
USER $APP_UID
ENV ASPNETCORE_HTTP_PORTS=8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "Helpdesk.Api.dll"]
FROM mcr.microsoft.com/dotnet/runtime:10.0 AS migrator
WORKDIR /app
COPY --from=build /out/migrator .
COPY db/migrations/ ./migrations/
USER $APP_UID
ENV MIGRATIONS_PATH=/app/migrations
ENTRYPOINT ["dotnet", "Helpdesk.Migrator.dll"]
+104
View File
@@ -0,0 +1,104 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Api", "src\Helpdesk.Api\Helpdesk.Api.csproj", "{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Application", "src\Helpdesk.Application\Helpdesk.Application.csproj", "{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Domain", "src\Helpdesk.Domain\Helpdesk.Domain.csproj", "{6C59E060-7E2E-4B28-BB59-C25472B509C7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Infrastructure", "src\Helpdesk.Infrastructure\Helpdesk.Infrastructure.csproj", "{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\Helpdesk.Migrator\Helpdesk.Migrator.csproj", "{B421E85C-F581-48BB-AB17-551339CEA5AD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|x64.ActiveCfg = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|x64.Build.0 = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|x86.ActiveCfg = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Debug|x86.Build.0 = Debug|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|Any CPU.Build.0 = Release|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|x64.ActiveCfg = Release|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|x64.Build.0 = Release|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|x86.ActiveCfg = Release|Any CPU
{4EAB3997-D5B3-4621-9E25-26B499A4E5C7}.Release|x86.Build.0 = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|x64.ActiveCfg = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|x64.Build.0 = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|x86.ActiveCfg = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Debug|x86.Build.0 = Debug|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|Any CPU.Build.0 = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|x64.ActiveCfg = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|x64.Build.0 = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|x86.ActiveCfg = Release|Any CPU
{6573B619-1EE2-4F9A-9310-A56ECEA6B6CE}.Release|x86.Build.0 = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|x64.ActiveCfg = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|x64.Build.0 = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|x86.ActiveCfg = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Debug|x86.Build.0 = Debug|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|Any CPU.Build.0 = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|x64.ActiveCfg = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|x64.Build.0 = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|x86.ActiveCfg = Release|Any CPU
{6C59E060-7E2E-4B28-BB59-C25472B509C7}.Release|x86.Build.0 = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|x64.ActiveCfg = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|x64.Build.0 = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|x86.ActiveCfg = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Debug|x86.Build.0 = Debug|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|Any CPU.Build.0 = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|x64.ActiveCfg = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|x64.Build.0 = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|x86.ActiveCfg = Release|Any CPU
{C3F2FDBA-40A5-4523-B9E3-0A4ADBE5F48D}.Release|x86.Build.0 = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|x64.ActiveCfg = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|x64.Build.0 = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|x86.ActiveCfg = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Debug|x86.Build.0 = Debug|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|Any CPU.Build.0 = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|x64.ActiveCfg = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|x64.Build.0 = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|x86.ActiveCfg = Release|Any CPU
{B421E85C-F581-48BB-AB17-551339CEA5AD}.Release|x86.Build.0 = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|x64.ActiveCfg = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|x64.Build.0 = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|x86.ActiveCfg = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Debug|x86.Build.0 = Debug|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|Any CPU.Build.0 = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.ActiveCfg = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+5
View File
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
@@ -0,0 +1,46 @@
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
/// <summary>Správa uživatelů a rolí (jen administrátor).</summary>
[ApiController]
[Authorize(Roles = Roles.Admin)]
[Route("api/admin/users")]
[Produces("application/json")]
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
{
/// <summary>Vyhledání uživatelů podle jména / e-mailu a role.</summary>
[HttpGet]
public Task<PagedResult<AdminUserDto>> Search(
[FromQuery] string? q, [FromQuery] string? role,
[FromQuery] int page = 1, [FromQuery] int pageSize = 20,
CancellationToken ct = default) =>
users.SearchAsync(q, role, page, pageSize, ct);
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
[HttpPut("{id:int}/role")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> ChangeRole(int id, ChangeRoleRequest request, CancellationToken ct)
{
await users.ChangeRoleAsync(currentUser, id, request, ct);
return NoContent();
}
/// <summary>Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele.</summary>
[HttpPut("{id:int}/active")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> SetActive(int id, SetActiveRequest request, CancellationToken ct)
{
await users.SetActiveAsync(currentUser, id, request, ct);
return NoContent();
}
}
@@ -0,0 +1,92 @@
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Helpdesk.Api.Controllers;
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
[ApiController]
[Route("api/auth")]
[EnableRateLimiting(RateLimitPolicies.Auth)]
[Produces("application/json")]
public sealed class AuthController(AuthService auth) : ControllerBase
{
/// <summary>Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
/// <remarks>Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit.</remarks>
[HttpPost("register")]
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
{
var user = await auth.RegisterAsync(request, ct);
return Created("/api/users/me", user);
}
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</summary>
[HttpPost("confirm-email")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ConfirmEmail(EmailTokenRequest request, CancellationToken ct)
{
await auth.ConfirmEmailAsync(request, ct);
return NoContent();
}
/// <summary>Přihlášení – vrací access token (15 min) a refresh token (14 dní).</summary>
[HttpPost("login")]
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
public Task<AuthResponse> Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct);
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
[HttpPost("refresh")]
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
public Task<AuthResponse> Refresh(RefreshTokenRequest request, CancellationToken ct) => auth.RefreshAsync(request, ct);
/// <summary>Odhlášení tohoto zařízení – zneplatní aktuální access token a předaný refresh token.</summary>
[Authorize]
[HttpPost("logout")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Logout(RefreshTokenRequest request, [FromServices] ICurrentUser currentUser, CancellationToken ct)
{
await auth.LogoutAsync(currentUser, request, ct);
return NoContent();
}
/// <summary>Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele.</summary>
[Authorize]
[HttpPost("logout-all")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> LogoutAll([FromServices] ICurrentUser currentUser, CancellationToken ct)
{
await auth.LogoutAllAsync(currentUser, ct);
return NoContent();
}
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
[HttpPost("forgot-password")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> ForgotPassword(ForgotPasswordRequest request, CancellationToken ct)
{
await auth.ForgotPasswordAsync(request, ct);
return NoContent();
}
/// <summary>Nastaví nové heslo tokenem z e-mailu; zneplatní všechna dosavadní přihlášení.</summary>
[HttpPost("reset-password")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword(ResetPasswordRequest request, CancellationToken ct)
{
await auth.ResetPasswordAsync(request, ct);
return NoContent();
}
}
@@ -0,0 +1,54 @@
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Catalogs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
/// <summary>Číselníky pro formuláře (budovy, kategorie závad a návrhů) a jejich správa.</summary>
[ApiController]
[Authorize]
[Route("api")]
[Produces("application/json")]
public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
{
/// <summary>Budovy. Administrátor může přidat <c>includeInactive=true</c> a vidět i deaktivované.</summary>
[HttpGet("buildings")]
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
[HttpGet("issue-categories")]
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct);
[HttpGet("proposal-categories")]
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct);
[Authorize(Roles = Roles.Admin)]
[HttpPost("buildings")]
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<BuildingDto>> CreateBuilding(SaveBuildingRequest request, CancellationToken ct)
{
var building = await catalogs.CreateBuildingAsync(request, ct);
return Created($"/api/buildings/{building.Id}", building);
}
[Authorize(Roles = Roles.Admin)]
[HttpPut("buildings/{id:int}")]
[ProducesResponseType<BuildingDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public Task<BuildingDto> UpdateBuilding(int id, SaveBuildingRequest request, CancellationToken ct) =>
catalogs.UpdateBuildingAsync(id, request, ct);
/// <summary>Deaktivace budovy – záznam se nemaže, jen se přestane nabízet ve formulářích.</summary>
[Authorize(Roles = Roles.Admin)]
[HttpDelete("buildings/{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeactivateBuilding(int id, CancellationToken ct)
{
await catalogs.DeactivateBuildingAsync(id, ct);
return NoContent();
}
}
@@ -0,0 +1,32 @@
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Api.Controllers;
public sealed record HealthResponse(string Status, string? SchemaVersion);
/// <summary>Stav služby a verze schématu DB (poslední provedená migrace, kap. 12.5).</summary>
[ApiController]
[Route("health")]
[Produces("application/json")]
public sealed class HealthController(HelpdeskDbContext db) : ControllerBase
{
[HttpGet]
[ProducesResponseType<HealthResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<HealthResponse>(StatusCodes.Status503ServiceUnavailable)]
public async Task<IActionResult> Get(CancellationToken ct)
{
try
{
var version = await db.Database
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid DESC LIMIT 1")
.FirstOrDefaultAsync(ct);
return Ok(new HealthResponse("Healthy", version));
}
catch (Exception) when (!ct.IsCancellationRequested)
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, new HealthResponse("Unhealthy", null));
}
}
}
@@ -0,0 +1,24 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
/// <summary>Profil přihlášeného uživatele.</summary>
[ApiController]
[Authorize]
[Route("api/users")]
[Produces("application/json")]
public sealed class UsersController(UserService users, ICurrentUser currentUser) : ControllerBase
{
/// <summary>Můj profil.</summary>
[HttpGet("me")]
public Task<UserDto> GetMe(CancellationToken ct) => users.GetMeAsync(currentUser, ct);
/// <summary>Úprava profilu – jméno, telefon (ukládá se šifrovaně), e-mailové notifikace.</summary>
[HttpPut("me")]
[ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct);
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- XML komentáře se používají pro Swagger; povinné nejsou u každého členu. -->
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Helpdesk.Application\Helpdesk.Application.csproj" />
<ProjectReference Include="..\Helpdesk.Infrastructure\Helpdesk.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Swashbuckle.AspNetCore" />
</ItemGroup>
</Project>
@@ -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;
}
}
+53
View File
@@ -0,0 +1,53 @@
using System.Threading.RateLimiting;
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application;
using Helpdesk.Application.Abstractions;
using Helpdesk.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApplication(builder.Configuration);
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
builder.Services.AddHelpdeskAuthentication(builder.Configuration);
builder.Services.AddAuthorization();
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddHelpdeskSwagger();
// Ochrana /api/auth/* proti hádání hesel a zahlcení (kap. 10).
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
});
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1");
options.DocumentTitle = "Helpdesk API";
});
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
/// <summary>Vstupní bod – veřejný kvůli integračním testům (WebApplicationFactory).</summary>
public partial class Program;
+25
View File
@@ -0,0 +1,25 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Helpdesk": ""
},
"Jwt": {
"Issuer": "https://helpdesk.localhost",
"SigningKey": ""
},
"Encryption": {
"Key": ""
},
"Registration": {
"StudentEmailDomains": [ "student.univerzita.cz" ],
"TeacherEmailDomains": [ "univerzita.cz" ],
"WebBaseUrl": "https://helpdesk.localhost"
}
}
@@ -0,0 +1,56 @@
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Abstractions;
public interface IAppDbContext
{
DbSet<User> Users { get; }
DbSet<AuthToken> AuthTokens { get; }
DbSet<Building> Buildings { get; }
DbSet<IssueCategory> IssueCategories { get; }
DbSet<ProposalCategory> ProposalCategories { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
public interface IPasswordHasher
{
string Hash(string password);
bool Verify(string password, string passwordHash);
}
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
public sealed record IssuedToken(string Token, AuthToken Record);
/// <summary>Ověřený token: identifikátor <c>jti</c> a uživatel (<c>sub</c>).</summary>
public sealed record ValidatedToken(string Jti, int UserId);
public interface ITokenService
{
IssuedToken Issue(User user, TokenType type);
/// <summary>Ověří podpis, <c>typ</c>, <c>iss</c>, <c>aud</c> a <c>exp</c> (RFC 7519, kap. 7.2). Neplatný token → <c>null</c>.</summary>
Task<ValidatedToken?> ValidateAsync(string token, TokenType expectedType);
}
/// <summary>Paměťová evidence zneplatněných access tokenů, které ještě nevypršely (kap. 10.1).</summary>
public interface IRevokedTokenStore
{
bool IsRevoked(string jti);
void Add(string jti, DateTime expiresAt);
}
public interface IEmailSender
{
Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default);
}
/// <summary>Přihlášený uživatel aktuálního požadavku (claimy access tokenu).</summary>
public interface ICurrentUser
{
int Id { get; }
string TokenId { get; }
}
@@ -0,0 +1,63 @@
using FluentValidation;
using Helpdesk.Application.Users;
namespace Helpdesk.Application.Auth;
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
public sealed record LoginRequest(string Email, string Password);
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
public sealed record RefreshTokenRequest(string RefreshToken);
/// <summary>Token z odkazu v e-mailu (ověření e-mailu).</summary>
public sealed record EmailTokenRequest(string Token);
public sealed record ForgotPasswordRequest(string Email);
public sealed record ResetPasswordRequest(string Token, string NewPassword);
public sealed record AuthResponse(
string AccessToken,
DateTime AccessTokenExpiresAt,
string RefreshToken,
DateTime RefreshTokenExpiresAt,
UserDto User);
internal static class PasswordRules
{
public const int MinLength = 8;
public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů
public static IRuleBuilderOptions<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) =>
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength);
}
public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
{
public RegisterRequestValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
RuleFor(x => x.Password).ValidPassword();
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
}
}
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
{
public LoginRequestValidator()
{
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
public sealed class ResetPasswordRequestValidator : AbstractValidator<ResetPasswordRequest>
{
public ResetPasswordRequestValidator()
{
RuleFor(x => x.Token).NotEmpty();
RuleFor(x => x.NewPassword).ValidPassword();
}
}
@@ -0,0 +1,36 @@
using Helpdesk.Domain.Users;
namespace Helpdesk.Application.Auth;
/// <summary>Konfigurace samoregistrace (sekce <c>Registration</c>).</summary>
public sealed class RegistrationOptions
{
public const string Section = "Registration";
/// <summary>Domény e-mailu, ze kterých vzniká role <c>STUDENT</c> (např. <c>student.univerzita.cz</c>).</summary>
public string[] StudentEmailDomains { get; set; } = [];
/// <summary>Domény e-mailu, ze kterých vzniká role <c>TEACHER</c> (např. <c>univerzita.cz</c>).</summary>
public string[] TeacherEmailDomains { get; set; } = [];
/// <summary>Adresa webové aplikace pro odkazy v e-mailech (ověření e-mailu, reset hesla).</summary>
public string WebBaseUrl { get; set; } = "https://helpdesk.localhost";
/// <summary>
/// Role podle domény e-mailu (kap. 2.1). Porovnává se celá doména, takže
/// <c>@student.univerzita.cz</c> nespadne pod <c>univerzita.cz</c>. Jiná doména → <c>null</c>.
/// </summary>
public UserRole? ResolveRole(string email)
{
var at = email.LastIndexOf('@');
if (at < 0)
return null;
var domain = email[(at + 1)..].Trim();
if (StudentEmailDomains.Contains(domain, StringComparer.OrdinalIgnoreCase))
return UserRole.Student;
if (TeacherEmailDomains.Contains(domain, StringComparer.OrdinalIgnoreCase))
return UserRole.Teacher;
return null;
}
}
@@ -0,0 +1,183 @@
using FluentValidation;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Users;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Helpdesk.Application.Auth;
/// <summary>Registrace, přihlášení a práce s tokeny (FR-01 – FR-03, kap. 10.1).</summary>
public sealed class AuthService(
IAppDbContext db,
IPasswordHasher passwordHasher,
ITokenService tokens,
TokenRevocationService revocation,
IEmailSender emailSender,
IOptions<RegistrationOptions> registrationOptions,
TimeProvider clock,
IValidator<RegisterRequest> registerValidator,
IValidator<LoginRequest> loginValidator,
IValidator<ResetPasswordRequest> resetPasswordValidator)
{
private readonly RegistrationOptions _registration = registrationOptions.Value;
public async Task<UserDto> RegisterAsync(RegisterRequest request, CancellationToken ct)
{
await registerValidator.ValidateAndThrowAsync(request, ct);
var role = _registration.ResolveRole(request.Email)
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
var normalized = User.NormalizeEmail(request.Email);
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct))
throw new ConflictException("Účet s tímto e-mailem už existuje.");
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
return UserDto.From(user);
}
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
{
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
user.ConfirmEmail();
await db.SaveChangesAsync(ct);
}
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
{
await loginValidator.ValidateAndThrowAsync(request, ct);
var now = clock.GetUtcNow().UtcDateTime;
var normalized = User.NormalizeEmail(request.Email);
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
if (user is null)
throw new UnauthorizedException(invalidCredentials);
if (user.IsLockedOut(now))
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
if (!passwordHasher.Verify(request.Password, user.PasswordHash))
{
user.RegisterFailedLogin(now);
await db.SaveChangesAsync(ct);
throw new UnauthorizedException(invalidCredentials);
}
if (!user.IsActive)
throw new ForbiddenException("Účet je deaktivován.");
if (!user.EmailConfirmed)
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z registračního e-mailu.");
user.RegisterSuccessfulLogin();
return await IssueTokenPairAsync(user, ct);
}
/// <summary>
/// Rotace refresh tokenu. Každý refresh token jde použít jen jednou; opakované použití
/// znamená, že token zneužil někdo jiný → zneplatní se všechny tokeny uživatele (kap. 10.1).
/// </summary>
public async Task<AuthResponse> RefreshAsync(RefreshTokenRequest request, CancellationToken ct)
{
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
?? throw new UnauthorizedException("Neplatný refresh token.");
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
{
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
}
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
if (user is null || !user.IsActive)
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
return await IssueTokenPairAsync(user, ct);
}
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
public async Task LogoutAsync(ICurrentUser currentUser, RefreshTokenRequest request, CancellationToken ct)
{
var jtis = new List<string> { currentUser.TokenId };
var refresh = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh);
if (refresh is not null && refresh.UserId == currentUser.Id)
jtis.Add(refresh.Jti);
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
}
public Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct) =>
revocation.RevokeAllAsync(currentUser.Id, RevokeReason.LogoutAll, ct);
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
{
var normalized = User.NormalizeEmail(request.Email ?? "");
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
if (user is not null)
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
}
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
{
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
// Nejdřív zneplatnit stará přihlášení – kdyby uložení hesla selhalo, nic se tím neotevře.
await revocation.RevokeAllAsync(user.Id, RevokeReason.PasswordChanged, ct);
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
await db.SaveChangesAsync(ct);
}
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
{
var access = tokens.Issue(user, TokenType.Access);
var refresh = tokens.Issue(user, TokenType.Refresh);
db.AuthTokens.AddRange(access.Record, refresh.Record);
await db.SaveChangesAsync(ct);
return new AuthResponse(
access.Token, access.Record.ExpiresAt,
refresh.Token, refresh.Record.ExpiresAt,
UserDto.From(user));
}
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
{
var issued = tokens.Issue(user, type);
db.AuthTokens.Add(issued.Record);
await db.SaveChangesAsync(ct);
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
var (subject, path, text) = type switch
{
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
_ => throw new ArgumentOutOfRangeException(nameof(type)),
};
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
}
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
{
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
if (!await revocation.TryConsumeAsync(validated.Jti, type, ct))
throw new BadRequestException(invalid);
return await db.Users.SingleOrDefaultAsync(u => u.Id == validated.UserId && u.IsActive, ct)
?? throw new BadRequestException(invalid);
}
}
@@ -0,0 +1,70 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Auth;
/// <summary>Zneplatňování tokenů v <c>auth_token</c> a současně v paměťové evidenci API.</summary>
public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore store, TimeProvider clock)
{
/// <summary>
/// Jednorázové použití tokenu: kontrola i zneplatnění jsou jeden atomický UPDATE (kap. 10.1).
/// Vrací <c>false</c>, pokud token už byl použitý nebo zneplatněný.
/// </summary>
public async Task<bool> TryConsumeAsync(string jti, TokenType type, CancellationToken ct)
{
var now = Now();
var updated = await db.AuthTokens
.Where(t => t.Jti == jti && t.TokenType == type && t.RevokedAt == null)
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.RevokedAt, now)
.SetProperty(t => t.RevokeReason, RevokeReason.Used), ct);
return updated == 1;
}
/// <summary>Zneplatní konkrétní tokeny uživatele (např. access a refresh token jednoho zařízení).</summary>
public async Task RevokeAsync(int userId, IReadOnlyCollection<string> jtis, RevokeReason reason, CancellationToken ct)
{
var now = Now();
await db.AuthTokens
.Where(t => t.UserId == userId && jtis.Contains(t.Jti) && t.RevokedAt == null)
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.RevokedAt, now)
.SetProperty(t => t.RevokeReason, reason), ct);
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
}
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
{
var now = Now();
await db.AuthTokens
.Where(t => t.UserId == userId && t.RevokedAt == null)
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.RevokedAt, now)
.SetProperty(t => t.RevokeReason, reason), ct);
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
}
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
private async Task AddRevokedAccessTokensToStoreAsync(int userId, DateTime revokedAt, CancellationToken ct)
{
var revoked = await db.AuthTokens
.AsNoTracking()
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
.Select(t => new { t.Jti, t.ExpiresAt })
.ToListAsync(ct);
foreach (var token in revoked)
store.Add(token.Jti, token.ExpiresAt);
}
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
private DateTime Now()
{
var now = clock.GetUtcNow().UtcDateTime;
return new DateTime(now.Ticks - now.Ticks % 10, DateTimeKind.Utc);
}
}
@@ -0,0 +1,90 @@
using FluentValidation;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain.Catalogs;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Catalogs;
public sealed record BuildingDto(int Id, string Code, string Name, string? Address, bool IsActive);
public sealed record CategoryDto(int Id, string Name, string? Description, bool IsActive);
public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
{
public SaveBuildingRequestValidator()
{
RuleFor(x => x.Code).NotEmpty().MaximumLength(20);
RuleFor(x => x.Name).NotEmpty().MaximumLength(150);
RuleFor(x => x.Address).MaximumLength(255);
}
}
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator)
{
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
await db.Buildings.AsNoTracking()
.Where(b => includeInactive || b.IsActive)
.OrderBy(b => b.Code)
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
.ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) =>
await db.IssueCategories.AsNoTracking()
.Where(c => c.IsActive)
.OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) =>
await db.ProposalCategories.AsNoTracking()
.Where(c => c.IsActive)
.OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct);
public async Task<BuildingDto> CreateBuildingAsync(SaveBuildingRequest request, CancellationToken ct)
{
await buildingValidator.ValidateAndThrowAsync(request, ct);
await EnsureUniqueCodeAsync(request.Code, null, ct);
var building = new Building(request.Code, request.Name, request.Address);
db.Buildings.Add(building);
await db.SaveChangesAsync(ct);
return ToDto(building);
}
public async Task<BuildingDto> UpdateBuildingAsync(int id, SaveBuildingRequest request, CancellationToken ct)
{
await buildingValidator.ValidateAndThrowAsync(request, ct);
var building = await GetBuildingAsync(id, ct);
await EnsureUniqueCodeAsync(request.Code, id, ct);
building.Update(request.Code, request.Name, request.Address);
await db.SaveChangesAsync(ct);
return ToDto(building);
}
public async Task DeactivateBuildingAsync(int id, CancellationToken ct)
{
var building = await GetBuildingAsync(id, ct);
building.SetActive(false);
await db.SaveChangesAsync(ct);
}
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
?? throw new NotFoundException($"Budova {id} neexistuje.");
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
{
var trimmed = code.Trim();
if (await db.Buildings.AnyAsync(b => b.Code == trimmed && b.Id != exceptId, ct))
throw new ConflictException($"Budova s kódem '{trimmed}' už existuje.");
}
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
}
@@ -0,0 +1,34 @@
namespace Helpdesk.Application.Common;
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
public abstract class AppException(string message) : Exception(message)
{
public abstract int StatusCode { get; }
}
public sealed class NotFoundException(string message) : AppException(message)
{
public override int StatusCode => 404;
}
public sealed class ConflictException(string message) : AppException(message)
{
public override int StatusCode => 409;
}
public sealed class ForbiddenException(string message) : AppException(message)
{
public override int StatusCode => 403;
}
public sealed class UnauthorizedException(string message) : AppException(message)
{
public override int StatusCode => 401;
}
public sealed class BadRequestException(string message) : AppException(message)
{
public override int StatusCode => 400;
}
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
@@ -0,0 +1,23 @@
using FluentValidation;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Users;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Helpdesk.Application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<RegistrationOptions>(configuration.GetSection(RegistrationOptions.Section));
services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly, includeInternalTypes: true);
services.AddScoped<TokenRevocationService>();
services.AddScoped<AuthService>();
services.AddScoped<UserService>();
services.AddScoped<CatalogService>();
return services;
}
}
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Helpdesk.Domain\Helpdesk.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Aplikační vrstva pracuje s DbSety přes IAppDbContext; konkrétní provider (MariaDB) je v Infrastructure. -->
<PackageReference Include="Microsoft.EntityFrameworkCore" />
<PackageReference Include="FluentValidation" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
</ItemGroup>
</Project>
@@ -0,0 +1,47 @@
using FluentValidation;
using Helpdesk.Domain;
using Helpdesk.Domain.Users;
namespace Helpdesk.Application.Users;
/// <summary>Profil uživatele. Role se vrací jako kód (<c>STUDENT</c>, <c>FACILITY_MANAGER</c>, …).</summary>
public sealed record UserDto(
int Id,
string Email,
string FirstName,
string LastName,
string? Phone,
string Role,
bool EmailNotificationsEnabled)
{
public static UserDto From(User user) => new(
user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled);
}
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProfileRequest>
{
public UpdateProfileRequestValidator()
{
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone))
.WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +.");
}
}
/// <summary>Uživatel v přehledu administrátora.</summary>
public sealed record AdminUserDto(
int Id,
string Email,
string FirstName,
string LastName,
string Role,
bool IsActive,
bool EmailConfirmed,
DateTime CreatedAt);
public sealed record ChangeRoleRequest(string Role);
public sealed record SetActiveRequest(bool IsActive);
@@ -0,0 +1,99 @@
using FluentValidation;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Users;
/// <summary>Vlastní profil (FR-05) a správa uživatelů administrátorem (FR-04).</summary>
public sealed class UserService(
IAppDbContext db,
TokenRevocationService revocation,
IValidator<UpdateProfileRequest> profileValidator)
{
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
UserDto.From(await GetAsync(currentUser.Id, ct));
public async Task<UserDto> UpdateMeAsync(ICurrentUser currentUser, UpdateProfileRequest request, CancellationToken ct)
{
await profileValidator.ValidateAndThrowAsync(request, ct);
var user = await GetAsync(currentUser.Id, ct);
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
await db.SaveChangesAsync(ct);
return UserDto.From(user);
}
public async Task<PagedResult<AdminUserDto>> SearchAsync(string? q, string? role, int page, int pageSize, CancellationToken ct)
{
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 1, 100);
var query = db.Users.AsNoTracking();
if (!string.IsNullOrWhiteSpace(q))
{
var term = q.Trim();
query = query.Where(u => u.Email.Contains(term) || u.FirstName.Contains(term) || u.LastName.Contains(term));
}
if (!string.IsNullOrWhiteSpace(role))
{
var parsed = ParseRole(role);
query = query.Where(u => u.Role == parsed);
}
var total = await query.CountAsync(ct);
var users = await query
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
.Skip((page - 1) * pageSize).Take(pageSize)
.ToListAsync(ct);
var items = users
.Select(u => new AdminUserDto(u.Id, u.Email, u.FirstName, u.LastName, u.Role.ToCode(), u.IsActive, u.EmailConfirmed, u.CreatedAt))
.ToList();
return new PagedResult<AdminUserDto>(items, total, page, pageSize);
}
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
public async Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
{
var role = ParseRole(request.Role);
if (userId == admin.Id)
throw new ConflictException("Administrátor nemůže změnit roli sám sobě.");
var user = await GetAsync(userId, ct);
if (user.Role == role)
return;
await revocation.RevokeAllAsync(user.Id, RevokeReason.RoleChanged, ct);
user.ChangeRole(role);
await db.SaveChangesAsync(ct);
}
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
{
if (userId == admin.Id && !request.IsActive)
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
var user = await GetAsync(userId, ct);
if (user.IsActive == request.IsActive)
return;
if (!request.IsActive)
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
user.SetActive(request.IsActive);
await db.SaveChangesAsync(ct);
}
private async Task<User> GetAsync(int id, CancellationToken ct) =>
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
?? throw new NotFoundException($"Uživatel {id} neexistuje.");
private static UserRole ParseRole(string code) =>
EnumCode.TryParse<UserRole>(code, out var role)
? role
: throw new BadRequestException($"Neznámá role '{code}'. Povolené: {string.Join(", ", Enum.GetValues<UserRole>().Select(r => r.ToCode()))}.");
}
@@ -0,0 +1,48 @@
namespace Helpdesk.Domain.Auth;
/// <summary>
/// Evidence vydaného JWT podle claimu <c>jti</c> (tabulka <c>auth_token</c>, kap. 10.1).
/// Neukládá se token ani jeho hash – jen identifikátor, vlastník a stav platnosti.
/// </summary>
public sealed class AuthToken
{
private AuthToken() { } // EF Core
public AuthToken(string jti, int userId, TokenType tokenType, DateTime issuedAt, DateTime expiresAt)
{
Jti = jti;
UserId = userId;
TokenType = tokenType;
IssuedAt = issuedAt;
ExpiresAt = expiresAt;
}
public string Jti { get; private set; } = null!;
public int UserId { get; private set; }
public TokenType TokenType { get; private set; }
public DateTime IssuedAt { get; private set; }
public DateTime ExpiresAt { get; private set; }
public DateTime? RevokedAt { get; private set; }
public RevokeReason? RevokeReason { get; private set; }
}
public enum TokenType
{
Access,
Refresh,
EmailConfirm,
PasswordReset,
}
public enum RevokeReason
{
/// <summary>Jednorázový token byl použit (rotace refresh tokenu, odkaz z e-mailu).</summary>
Used,
Logout,
LogoutAll,
PasswordChanged,
RoleChanged,
AccountDeactivated,
/// <summary>Opakované použití refresh tokenu – podezření na krádež.</summary>
ReuseDetected,
}
@@ -0,0 +1,49 @@
namespace Helpdesk.Domain.Catalogs;
/// <summary>Budova / lokalita. Číselníky se nemažou, jen deaktivují.</summary>
public sealed class Building
{
private Building() { } // EF Core
public Building(string code, string name, string? address)
{
Update(code, name, address);
}
public int Id { get; private set; }
public string Code { get; private set; } = null!;
public string Name { get; private set; } = null!;
public string? Address { get; private set; }
public bool IsActive { get; private set; } = true;
public void Update(string code, string name, string? address)
{
Code = code.Trim();
Name = name.Trim();
Address = string.IsNullOrWhiteSpace(address) ? null : address.Trim();
}
public void SetActive(bool isActive) => IsActive = isActive;
}
/// <summary>Typ závady (tabulka <c>issue_category</c>).</summary>
public sealed class IssueCategory
{
private IssueCategory() { } // EF Core
public int Id { get; private set; }
public string Name { get; private set; } = null!;
public string? Description { get; private set; }
public bool IsActive { get; private set; } = true;
}
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
public sealed class ProposalCategory
{
private ProposalCategory() { } // EF Core
public int Id { get; private set; }
public string Name { get; private set; } = null!;
public string? Description { get; private set; }
public bool IsActive { get; private set; } = true;
}
+48
View File
@@ -0,0 +1,48 @@
using System.Collections.Concurrent;
using System.Text;
namespace Helpdesk.Domain;
/// <summary>
/// Převod hodnot enumů na textové kódy používané v DB, v JWT i v API
/// (<c>FacilityManager</c> ↔ <c>FACILITY_MANAGER</c>).
/// </summary>
public static class EnumCode
{
private static readonly ConcurrentDictionary<Enum, string> Codes = new();
public static string ToCode<TEnum>(this TEnum value) where TEnum : struct, Enum =>
Codes.GetOrAdd(value, v => ToScreamingSnake(v.ToString()));
public static TEnum Parse<TEnum>(string code) where TEnum : struct, Enum =>
TryParse<TEnum>(code, out var value)
? value
: throw new ArgumentException($"Neznámý kód '{code}' pro {typeof(TEnum).Name}.", nameof(code));
public static bool TryParse<TEnum>(string? code, out TEnum value) where TEnum : struct, Enum
{
foreach (var candidate in Enum.GetValues<TEnum>())
{
if (string.Equals(candidate.ToCode(), code, StringComparison.Ordinal))
{
value = candidate;
return true;
}
}
value = default;
return false;
}
private static string ToScreamingSnake(string name)
{
var sb = new StringBuilder(name.Length + 4);
for (var i = 0; i < name.Length; i++)
{
if (i > 0 && char.IsUpper(name[i]))
sb.Append('_');
sb.Append(char.ToUpperInvariant(name[i]));
}
return sb.ToString();
}
}
@@ -0,0 +1,2 @@
<Project Sdk="Microsoft.NET.Sdk">
</Project>
@@ -0,0 +1,7 @@
namespace Helpdesk.Domain;
/// <summary>Entita s neměnným časem vytvoření; vyplňuje ho interceptor při SaveChanges (kap. 12.4).</summary>
public interface IHasCreatedAt
{
DateTime CreatedAt { get; set; }
}
+82
View File
@@ -0,0 +1,82 @@
namespace Helpdesk.Domain.Users;
/// <summary>
/// Uživatelský účet (tabulka <c>app_user</c>). Entita záměrně nemá žádné kolekce
/// (závady, události, …) – vazby se konfigurují jen ze závislé strany (kap. 12.3).
/// </summary>
public sealed class User : IHasCreatedAt
{
public const int MaxFailedLogins = 5;
public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15);
private User() { } // EF Core
public int Id { get; private set; }
public string Email { get; private set; } = null!;
public string EmailNormalized { get; private set; } = null!;
public string PasswordHash { get; private set; } = null!;
public string FirstName { get; private set; } = null!;
public string LastName { get; private set; } = null!;
/// <summary>Telefon v otevřené podobě; v DB je šifrovaný (AES-256-GCM, sloupec <c>phone_encrypted</c>).</summary>
public string? Phone { get; private set; }
public UserRole Role { get; private set; }
public bool IsActive { get; private set; } = true;
public bool EmailConfirmed { get; private set; }
public bool EmailNotificationsEnabled { get; private set; } = true;
public int FailedLoginCount { get; private set; }
public DateTime? LockoutUntil { get; private set; }
public DateTime CreatedAt { get; set; }
public string FullName => $"{FirstName} {LastName}";
public static User Create(string email, string passwordHash, string firstName, string lastName, UserRole role) => new()
{
Email = email.Trim(),
EmailNormalized = NormalizeEmail(email),
PasswordHash = passwordHash,
FirstName = firstName.Trim(),
LastName = lastName.Trim(),
Role = role,
};
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now;
/// <summary>Neúspěšné přihlášení; po <see cref="MaxFailedLogins"/> pokusech se účet na 15 minut zamkne.</summary>
public void RegisterFailedLogin(DateTime now)
{
FailedLoginCount++;
if (FailedLoginCount >= MaxFailedLogins)
{
LockoutUntil = now + LockoutDuration;
FailedLoginCount = 0;
}
}
public void RegisterSuccessfulLogin()
{
FailedLoginCount = 0;
LockoutUntil = null;
}
public void ConfirmEmail() => EmailConfirmed = true;
public void ChangePasswordHash(string passwordHash)
{
PasswordHash = passwordHash;
RegisterSuccessfulLogin();
}
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
{
FirstName = firstName.Trim();
LastName = lastName.Trim();
Phone = string.IsNullOrWhiteSpace(phone) ? null : phone.Trim();
EmailNotificationsEnabled = emailNotificationsEnabled;
}
public void ChangeRole(UserRole role) => Role = role;
public void SetActive(bool isActive) => IsActive = isActive;
}
@@ -0,0 +1,11 @@
namespace Helpdesk.Domain.Users;
/// <summary>Role uživatele – každý uživatel má právě jednu (kap. 2.1). V DB a v JWT jako kód, např. <c>FACILITY_MANAGER</c>.</summary>
public enum UserRole
{
Student,
Teacher,
FacilityManager,
Management,
Admin,
}
@@ -0,0 +1,45 @@
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Background;
/// <summary>Jednou denně smaže záznamy <c>auth_token</c> 30 dní po vypršení; do té doby slouží jako audit (kap. 10.1).</summary>
internal sealed partial class AuthTokenCleanupService(
IServiceScopeFactory scopes,
TimeProvider clock,
ILogger<AuthTokenCleanupService> logger) : BackgroundService
{
private static readonly TimeSpan RetentionAfterExpiry = TimeSpan.FromDays(30);
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(Interval, clock);
do
{
try
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var threshold = clock.GetUtcNow().UtcDateTime - RetentionAfterExpiry;
var deleted = await db.AuthTokens.Where(t => t.ExpiresAt < threshold).ExecuteDeleteAsync(stoppingToken);
LogDeleted(deleted);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogFailed(ex);
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
[LoggerMessage(Level = LogLevel.Information, Message = "Úklid auth_token: smazáno {Count} prošlých záznamů.")]
private partial void LogDeleted(int count);
[LoggerMessage(Level = LogLevel.Error, Message = "Úklid auth_token selhal.")]
private partial void LogFailed(Exception ex);
}
@@ -0,0 +1,41 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Infrastructure.Background;
using Helpdesk.Infrastructure.Email;
using Helpdesk.Infrastructure.Persistence;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Helpdesk.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("Helpdesk")
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
services.AddSingleton(TimeProvider.System);
services.Configure<JwtOptions>(configuration.GetSection(JwtOptions.Section));
services.Configure<EncryptionOptions>(configuration.GetSection(EncryptionOptions.Section));
services.AddSingleton<FieldEncryptor>();
services.AddSingleton<CreatedAtInterceptor>();
services.AddDbContext<HelpdeskDbContext>((sp, options) => options
.UseMySql(connectionString, new MariaDbServerVersion(new Version(11, 4)))
.UseSnakeCaseNamingConvention()
.AddInterceptors(sp.GetRequiredService<CreatedAtInterceptor>()));
services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<HelpdeskDbContext>());
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
services.AddSingleton<ITokenService, JwtTokenService>();
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
services.AddSingleton<IEmailSender, LoggingEmailSender>();
services.AddHostedService<RevokedTokenStoreLoader>();
services.AddHostedService<AdminSeeder>();
services.AddHostedService<AuthTokenCleanupService>();
return services;
}
}
@@ -0,0 +1,20 @@
using Helpdesk.Application.Abstractions;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Email;
/// <summary>
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
/// </summary>
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
{
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
{
LogEmail(to, subject, body);
return Task.CompletedTask;
}
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
private partial void LogEmail(string to, string subject, string body);
}
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Helpdesk.Application\Helpdesk.Application.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" />
<PackageReference Include="MySqlConnector" />
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="BCrypt.Net-Next" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Helpdesk.UnitTests" />
</ItemGroup>
</Project>
@@ -0,0 +1,46 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Persistence;
/// <summary>
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
/// </summary>
internal sealed partial class AdminSeeder(
IServiceScopeFactory scopes,
IConfiguration configuration,
ILogger<AdminSeeder> logger) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
var email = configuration["ADMIN_EMAIL"];
var password = configuration["ADMIN_PASSWORD"];
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
return;
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
var normalized = User.NormalizeEmail(email);
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
return;
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
admin.ConfirmEmail();
db.Users.Add(admin);
await db.SaveChangesAsync(cancellationToken);
LogCreated(email);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
[LoggerMessage(Level = LogLevel.Information, Message = "Vytvořen účet administrátora {Email}.")]
private partial void LogCreated(string email);
}
@@ -0,0 +1,60 @@
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Helpdesk.Infrastructure.Persistence;
internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> b)
{
b.ToTable("app_user");
b.HasKey(u => u.Id);
b.Property(u => u.Email).HasMaxLength(254);
b.Property(u => u.EmailNormalized).HasMaxLength(254);
b.HasIndex(u => u.EmailNormalized).IsUnique();
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
b.Property(u => u.Phone)
.HasColumnName("phone_encrypted")
.HasConversion(encryptor.StringToCipherConverter)
.HasMaxLength(512);
b.Ignore(u => u.FullName);
}
}
internal sealed class AuthTokenConfiguration : IEntityTypeConfiguration<AuthToken>
{
public void Configure(EntityTypeBuilder<AuthToken> b)
{
b.ToTable("auth_token");
b.HasKey(t => t.Jti);
b.Property(t => t.Jti).HasMaxLength(36);
b.Property(t => t.TokenType).HasConversion<EnumCodeConverter<TokenType>>().HasMaxLength(20);
b.Property(t => t.RevokeReason).HasConversion<EnumCodeConverter<RevokeReason>>().HasMaxLength(30);
// Vazba jen ze závislé strany – User nemá kolekci tokenů (kap. 12.3).
b.HasOne<User>().WithMany().HasForeignKey(t => t.UserId);
}
}
internal sealed class BuildingConfiguration : IEntityTypeConfiguration<Building>
{
public void Configure(EntityTypeBuilder<Building> b)
{
b.ToTable("building");
b.HasKey(x => x.Id);
b.HasIndex(x => x.Code).IsUnique();
}
}
internal sealed class IssueCategoryConfiguration : IEntityTypeConfiguration<IssueCategory>
{
public void Configure(EntityTypeBuilder<IssueCategory> b) => b.ToTable("issue_category");
}
internal sealed class ProposalCategoryConfiguration : IEntityTypeConfiguration<ProposalCategory>
{
public void Configure(EntityTypeBuilder<ProposalCategory> b) => b.ToTable("proposal_category");
}
@@ -0,0 +1,35 @@
using Helpdesk.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Helpdesk.Infrastructure.Persistence;
/// <summary>Vyplní <c>created_at</c> u nově přidaných entit s <see cref="IHasCreatedAt"/> (kap. 12.4).</summary>
internal sealed class CreatedAtInterceptor(TimeProvider clock) : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
Stamp(eventData.Context);
return result;
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
Stamp(eventData.Context);
return ValueTask.FromResult(result);
}
private void Stamp(DbContext? context)
{
if (context is null)
return;
var now = clock.GetUtcNow().UtcDateTime;
foreach (var entry in context.ChangeTracker.Entries<IHasCreatedAt>())
{
if (entry.State == EntityState.Added)
entry.Entity.CreatedAt = now;
}
}
}
@@ -0,0 +1,10 @@
using Helpdesk.Domain;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Helpdesk.Infrastructure.Persistence;
/// <summary>Enum ↔ textový kód v DB (<c>FacilityManager</c> ↔ <c>'FACILITY_MANAGER'</c>), hodnoty hlídá CHECK omezení.</summary>
internal sealed class EnumCodeConverter<TEnum>() : ValueConverter<TEnum, string>(
v => v.ToCode(),
v => EnumCode.Parse<TEnum>(v))
where TEnum : struct, Enum;
@@ -0,0 +1,43 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Helpdesk.Infrastructure.Persistence;
/// <summary>
/// EF Core slouží jen k mapování – schéma vytvářejí SQL migrace v <c>db/migrations</c> (kap. 12.5).
/// Názvy sloupců jsou snake_case (EFCore.NamingConventions), tabulky jsou pojmenované explicitně.
/// </summary>
public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> options, FieldEncryptor encryptor)
: DbContext(options), IAppDbContext
{
public DbSet<User> Users => Set<User>();
public DbSet<AuthToken> AuthTokens => Set<AuthToken>();
public DbSet<Building> Buildings => Set<Building>();
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor));
modelBuilder.ApplyConfiguration(new AuthTokenConfiguration());
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
}
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
configurationBuilder.Properties<DateTime?>().HaveConversion<UtcDateTimeConverter>();
}
private sealed class UtcDateTimeConverter() : ValueConverter<DateTime, DateTime>(
v => v.Kind == DateTimeKind.Utc ? v : v.ToUniversalTime(),
v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
}
@@ -0,0 +1,13 @@
using Helpdesk.Application.Abstractions;
namespace Helpdesk.Infrastructure.Security;
/// <summary>BCrypt s work factorem 12; sůl je součástí hashe (kap. 10).</summary>
internal sealed class BCryptPasswordHasher : IPasswordHasher
{
private const int WorkFactor = 12;
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
}
@@ -0,0 +1,68 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.Options;
namespace Helpdesk.Infrastructure.Security;
public sealed class EncryptionOptions
{
public const string Section = "Encryption";
/// <summary>256bitový klíč v Base64 (proměnná prostředí <c>Encryption__Key</c>), nikdy není v DB ani v Gitu.</summary>
public string Key { get; set; } = "";
}
/// <summary>
/// Šifrování citlivých údajů AES-256-GCM (kap. 10). Uložený formát: nonce (12 B) | tag (16 B) | šifrovaný text.
/// GCM zároveň ověřuje integritu – pozměněná data se nepodaří dešifrovat.
/// </summary>
public sealed class FieldEncryptor
{
private const int NonceSize = 12;
private const int TagSize = 16;
private readonly byte[] _key;
public FieldEncryptor(IOptions<EncryptionOptions> options)
{
try
{
_key = Convert.FromBase64String(options.Value.Key);
}
catch (FormatException)
{
throw new InvalidOperationException("Encryption:Key musí být v Base64.");
}
if (_key.Length != 32)
throw new InvalidOperationException("Encryption:Key musí mít 32 bajtů (256 bitů) v Base64.");
StringToCipherConverter = new ValueConverter<string?, byte[]?>(
v => v == null ? null : Encrypt(v),
v => v == null ? null : Decrypt(v));
}
public ValueConverter<string?, byte[]?> StringToCipherConverter { get; }
public byte[] Encrypt(string plaintext)
{
var plain = Encoding.UTF8.GetBytes(plaintext);
var output = new byte[NonceSize + TagSize + plain.Length];
var nonce = output.AsSpan(0, NonceSize);
RandomNumberGenerator.Fill(nonce);
using var aes = new AesGcm(_key, TagSize);
aes.Encrypt(nonce, plain, output.AsSpan(NonceSize + TagSize), output.AsSpan(NonceSize, TagSize));
return output;
}
public string Decrypt(byte[] data)
{
if (data.Length < NonceSize + TagSize)
throw new CryptographicException("Šifrovaná hodnota je příliš krátká.");
var plain = new byte[data.Length - NonceSize - TagSize];
using var aes = new AesGcm(_key, TagSize);
aes.Decrypt(data.AsSpan(0, NonceSize), data.AsSpan(NonceSize + TagSize), data.AsSpan(NonceSize, TagSize), plain);
return Encoding.UTF8.GetString(plain);
}
}
@@ -0,0 +1,134 @@
using System.Security.Claims;
using System.Text;
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace Helpdesk.Infrastructure.Security;
public sealed class JwtOptions
{
public const string Section = "Jwt";
public string Issuer { get; set; } = "https://helpdesk.localhost";
/// <summary>Podpisový klíč HS256, alespoň 32 bajtů (proměnná prostředí <c>Jwt__SigningKey</c>).</summary>
public string SigningKey { get; set; } = "";
public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromMinutes(15);
public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(14);
public TimeSpan EmailConfirmLifetime { get; set; } = TimeSpan.FromHours(24);
public TimeSpan PasswordResetLifetime { get; set; } = TimeSpan.FromHours(1);
}
/// <summary>
/// Vydávání a ověřování JWT podle RFC 7519 (kap. 10.1). Druh tokenu určuje hlavička <c>typ</c>,
/// takže token jednoho druhu nejde použít místo jiného (RFC 8725, kap. 3.11).
/// </summary>
public sealed class JwtTokenService(IOptions<JwtOptions> options, TimeProvider clock) : ITokenService
{
public const string ApiAudience = "helpdesk-api";
public const string AuthAudience = "helpdesk-auth";
public const string RoleClaim = "role";
/// <summary>Povolená odchylka hodin; výchozích 5 minut v .NET je pro 15minutový token příliš.</summary>
public static readonly TimeSpan ClockSkew = TimeSpan.FromSeconds(30);
private readonly JwtOptions _options = options.Value;
private readonly JsonWebTokenHandler _handler = new() { SetDefaultTimesOnTokenCreation = false };
public static string HeaderType(TokenType type) => type switch
{
TokenType.Access => "at+jwt", // RFC 9068
TokenType.Refresh => "refresh+jwt",
TokenType.EmailConfirm => "email-confirm+jwt",
TokenType.PasswordReset => "password-reset+jwt",
_ => throw new ArgumentOutOfRangeException(nameof(type)),
};
public static SymmetricSecurityKey CreateSigningKey(string signingKey)
{
var bytes = Encoding.UTF8.GetBytes(signingKey);
if (bytes.Length < 32)
throw new InvalidOperationException("Jwt:SigningKey musí mít alespoň 32 bajtů.");
return new SymmetricSecurityKey(bytes);
}
/// <summary>Parametry ověření (RFC 7519, kap. 7.2): jen HS256, správný typ, vydavatel, příjemce a platnost.</summary>
public static TokenValidationParameters CreateValidationParameters(JwtOptions options, TokenType type) => new()
{
IssuerSigningKey = CreateSigningKey(options.SigningKey),
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
ValidTypes = [HeaderType(type)],
ValidIssuer = options.Issuer,
ValidAudience = Audience(type),
RequireExpirationTime = true,
RequireSignedTokens = true,
ClockSkew = ClockSkew,
NameClaimType = JwtRegisteredClaimNames.Sub,
RoleClaimType = RoleClaim,
};
public IssuedToken Issue(User user, TokenType type)
{
// DATETIME(6) i NumericDate – zaokrouhlení na celé sekundy, aby claimy a řádek v DB seděly.
var now = clock.GetUtcNow().UtcDateTime;
var issuedAt = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Utc);
var expiresAt = issuedAt + Lifetime(type);
var jti = Guid.NewGuid().ToString();
var claims = new Dictionary<string, object>
{
[JwtRegisteredClaimNames.Sub] = user.Id.ToString(),
[JwtRegisteredClaimNames.Jti] = jti,
};
if (type == TokenType.Access)
claims[RoleClaim] = user.Role.ToCode();
var token = _handler.CreateToken(new SecurityTokenDescriptor
{
TokenType = HeaderType(type),
Issuer = _options.Issuer,
Audience = Audience(type),
IssuedAt = issuedAt,
Expires = expiresAt,
Claims = claims,
SigningCredentials = new SigningCredentials(CreateSigningKey(_options.SigningKey), SecurityAlgorithms.HmacSha256),
});
return new IssuedToken(token, new AuthToken(jti, user.Id, type, issuedAt, expiresAt));
}
public async Task<ValidatedToken?> ValidateAsync(string token, TokenType expectedType)
{
if (string.IsNullOrWhiteSpace(token))
return null;
var parameters = CreateValidationParameters(_options, expectedType);
parameters.LifetimeValidator = (notBefore, expires, _, p) =>
expires is { } exp && clock.GetUtcNow().UtcDateTime <= exp.ToUniversalTime() + p.ClockSkew;
var result = await _handler.ValidateTokenAsync(token, parameters);
if (!result.IsValid || result.SecurityToken is not JsonWebToken jwt)
return null;
return int.TryParse(jwt.Subject, out var userId) && !string.IsNullOrEmpty(jwt.Id)
? new ValidatedToken(jwt.Id, userId)
: null;
}
private static string Audience(TokenType type) => type == TokenType.Access ? ApiAudience : AuthAudience;
private TimeSpan Lifetime(TokenType type) => type switch
{
TokenType.Access => _options.AccessTokenLifetime,
TokenType.Refresh => _options.RefreshTokenLifetime,
TokenType.EmailConfirm => _options.EmailConfirmLifetime,
TokenType.PasswordReset => _options.PasswordResetLifetime,
_ => throw new ArgumentOutOfRangeException(nameof(type)),
};
}
@@ -0,0 +1,67 @@
using System.Collections.Concurrent;
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Helpdesk.Infrastructure.Security;
/// <summary>
/// Zneplatněné access tokeny, které ještě nevypršely (kap. 10.1). Kontrola při každém požadavku
/// tak nejde do DB. Prošlé záznamy se průběžně odstraňují – prošlý token odmítne už kontrola <c>exp</c>.
/// API běží v jedné instanci; při více instancích by se nahradila sdílenou cache (Redis).
/// </summary>
internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
{
private readonly ConcurrentDictionary<string, DateTime> _revoked = new();
private long _lastPruneTicks;
public bool IsRevoked(string jti)
{
PruneOccasionally();
return _revoked.ContainsKey(jti);
}
public void Add(string jti, DateTime expiresAt)
{
if (expiresAt > clock.GetUtcNow().UtcDateTime)
_revoked[jti] = expiresAt;
}
private void PruneOccasionally()
{
var now = clock.GetUtcNow().UtcDateTime;
var last = Interlocked.Read(ref _lastPruneTicks);
if (now.Ticks - last < TimeSpan.TicksPerMinute || Interlocked.CompareExchange(ref _lastPruneTicks, now.Ticks, last) != last)
return;
foreach (var (jti, expiresAt) in _revoked)
{
if (expiresAt <= now)
_revoked.TryRemove(jti, out _);
}
}
}
/// <summary>Při startu API načte z DB zneplatněné access tokeny, které ještě platí.</summary>
internal sealed class RevokedTokenStoreLoader(IServiceScopeFactory scopes, IRevokedTokenStore store, TimeProvider clock) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var now = clock.GetUtcNow().UtcDateTime;
var revoked = await db.AuthTokens.AsNoTracking()
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
.Select(t => new { t.Jti, t.ExpiresAt })
.ToListAsync(cancellationToken);
foreach (var token in revoked)
store.Add(token.Jti, token.ExpiresAt);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="dbup-mysql" />
<PackageReference Include="MySqlConnector" />
</ItemGroup>
</Project>
+55
View File
@@ -0,0 +1,55 @@
// Helpdesk.Migrator – aplikuje SQL migrace z db/migrations (kap. 12.5).
//
// Konfigurace (proměnné prostředí):
// ConnectionStrings__Migrator připojení účtem helpdesk_migrator (smí měnit schéma)
// MIGRATIONS_PATH složka se skripty V{NNN}__{popis}.sql (výchozí: ./migrations)
//
// Provedené skripty eviduje tabulka schema_version a znovu se nespouštějí.
// Návratový kód 0 = úspěch; v Docker Compose na něm závisí start API.
using DbUp;
using DbUp.Engine;
using MySqlConnector;
var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings__Migrator");
if (string.IsNullOrWhiteSpace(connectionString))
{
Console.Error.WriteLine("Chybí proměnná prostředí ConnectionStrings__Migrator.");
return 2;
}
var migrationsPath = Path.GetFullPath(Environment.GetEnvironmentVariable("MIGRATIONS_PATH") ?? "migrations");
if (!Directory.Exists(migrationsPath))
{
Console.Error.WriteLine($"Složka s migracemi neexistuje: {migrationsPath}");
return 2;
}
var database = new MySqlConnectionStringBuilder(connectionString).Database;
var upgrader = DeployChanges.To
.MySqlDatabase(connectionString)
.WithScriptsFromFileSystem(migrationsPath, new DbUp.ScriptProviders.FileSystemScriptOptions
{
Filter = path => Path.GetFileName(path).StartsWith('V') && path.EndsWith(".sql", StringComparison.OrdinalIgnoreCase),
})
// MariaDB provádí DDL s implicitním commitem – transakce kolem skriptu by nic nevrátila.
.WithoutTransaction()
.JournalToMySqlTable(database, "schema_version")
.LogToConsole()
.Build();
var pending = upgrader.GetScriptsToExecute();
Console.WriteLine(pending.Count == 0
? "Databáze je aktuální, žádná migrace k provedení."
: $"Migrace k provedení: {string.Join(", ", pending.Select(s => s.Name))}");
DatabaseUpgradeResult result = upgrader.PerformUpgrade();
if (!result.Successful)
{
Console.Error.WriteLine($"Migrace selhala ve skriptu {result.ErrorScript?.Name}: {result.Error.Message}");
return 1;
}
Console.WriteLine("Migrace dokončeny.");
return 0;
@@ -0,0 +1,102 @@
using Helpdesk.Application.Auth;
using Helpdesk.Domain;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
namespace Helpdesk.UnitTests;
public class EnumCodeTests
{
[Theory]
[InlineData(UserRole.Student, "STUDENT")]
[InlineData(UserRole.FacilityManager, "FACILITY_MANAGER")]
[InlineData(UserRole.Management, "MANAGEMENT")]
public void UserRole_ma_kod_odpovidajici_check_omezeni(UserRole role, string code)
{
Assert.Equal(code, role.ToCode());
Assert.Equal(role, EnumCode.Parse<UserRole>(code));
}
[Theory]
[InlineData(TokenType.EmailConfirm, "EMAIL_CONFIRM")]
[InlineData(TokenType.PasswordReset, "PASSWORD_RESET")]
[InlineData(RevokeReason.ReuseDetected, "REUSE_DETECTED")]
[InlineData(RevokeReason.LogoutAll, "LOGOUT_ALL")]
public void Kody_tokenu_odpovidaji_check_omezeni(object value, string code)
{
var actual = value switch
{
TokenType t => t.ToCode(),
RevokeReason r => r.ToCode(),
_ => throw new ArgumentException(null, nameof(value)),
};
Assert.Equal(code, actual);
}
[Fact]
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
}
public class UserLockoutTests
{
private static readonly DateTime Now = new(2026, 10, 29, 10, 0, 0, DateTimeKind.Utc);
private static User NewUser() => User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student);
[Fact]
public void Ctyri_neuspesne_pokusy_ucet_nezamknou()
{
var user = NewUser();
for (var i = 0; i < User.MaxFailedLogins - 1; i++)
user.RegisterFailedLogin(Now);
Assert.False(user.IsLockedOut(Now));
}
[Fact]
public void Paty_neuspesny_pokus_zamkne_ucet_na_15_minut()
{
var user = NewUser();
for (var i = 0; i < User.MaxFailedLogins; i++)
user.RegisterFailedLogin(Now);
Assert.True(user.IsLockedOut(Now.AddMinutes(14)));
Assert.False(user.IsLockedOut(Now.AddMinutes(15)));
}
[Fact]
public void Uspesne_prihlaseni_vynuluje_pocitadlo()
{
var user = NewUser();
user.RegisterFailedLogin(Now);
user.RegisterSuccessfulLogin();
Assert.Equal(0, user.FailedLoginCount);
}
[Fact]
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
Assert.Equal("[email protected]", NewUser().EmailNormalized);
}
public class RegistrationRoleTests
{
private readonly RegistrationOptions _options = new()
{
StudentEmailDomains = ["student.univerzita.cz"],
TeacherEmailDomains = ["univerzita.cz"],
};
[Theory]
[InlineData("[email protected]", UserRole.Student)]
[InlineData("[email protected]", UserRole.Teacher)]
[InlineData("[email protected]", UserRole.Teacher)]
public void Role_se_urci_podle_domeny(string email, UserRole expected) =>
Assert.Equal(expected, _options.ResolveRole(email));
[Theory]
[InlineData("[email protected]")]
[InlineData("[email protected]")]
[InlineData("bez-zavinace")]
public void Cizi_domena_registraci_neumozni(string email) => Assert.Null(_options.ResolveRole(email));
}
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Helpdesk.Infrastructure\Helpdesk.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
@@ -0,0 +1,130 @@
using System.Security.Cryptography;
using System.Text;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Helpdesk.UnitTests;
public class JwtTokenServiceTests
{
private readonly FakeClock _clock = new(new DateTimeOffset(2026, 10, 29, 10, 0, 0, TimeSpan.Zero));
private readonly JwtTokenService _service;
private readonly User _user = User.Create("[email protected]", "hash", "Petr", "Svoboda", UserRole.FacilityManager);
public JwtTokenServiceTests()
{
_service = new JwtTokenService(Options.Create(new JwtOptions
{
Issuer = "https://test",
SigningKey = "test-signing-key-ktery-ma-aspon-32-bajtu",
}), _clock);
}
[Fact]
public void Access_token_ma_typ_v_hlavicce_a_registrovane_claimy()
{
var issued = _service.Issue(_user, TokenType.Access);
var jwt = new JsonWebToken(issued.Token);
Assert.Equal("at+jwt", jwt.Typ);
Assert.Equal("HS256", jwt.Alg);
Assert.Equal("https://test", jwt.Issuer);
Assert.Equal(["helpdesk-api"], jwt.Audiences);
Assert.Equal(issued.Record.Jti, jwt.Id);
Assert.Equal("FACILITY_MANAGER", jwt.GetClaim("role").Value);
Assert.False(jwt.TryGetClaim("nbf", out _));
Assert.False(jwt.TryGetClaim("email", out _)); // žádné osobní údaje v tokenu
Assert.Equal(TimeSpan.FromMinutes(15), issued.Record.ExpiresAt - issued.Record.IssuedAt);
}
[Fact]
public async Task Refresh_token_projde_jen_jako_refresh()
{
var refresh = _service.Issue(_user, TokenType.Refresh);
Assert.NotNull(await _service.ValidateAsync(refresh.Token, TokenType.Refresh));
Assert.Null(await _service.ValidateAsync(refresh.Token, TokenType.PasswordReset));
Assert.Null(await _service.ValidateAsync(refresh.Token, TokenType.Access));
}
[Fact]
public async Task Access_token_nejde_pouzit_jako_refresh()
{
var access = _service.Issue(_user, TokenType.Access);
Assert.Null(await _service.ValidateAsync(access.Token, TokenType.Refresh));
}
[Fact]
public async Task Prosly_token_se_odmitne()
{
var reset = _service.Issue(_user, TokenType.PasswordReset);
_clock.Advance(TimeSpan.FromHours(1) + JwtTokenService.ClockSkew + TimeSpan.FromSeconds(1));
Assert.Null(await _service.ValidateAsync(reset.Token, TokenType.PasswordReset));
}
[Fact]
public async Task Pozmeneny_token_se_odmitne()
{
var refresh = _service.Issue(_user, TokenType.Refresh).Token;
var tampered = refresh[..^2] + (refresh[^2] == 'A' ? "BB" : "AA");
Assert.Null(await _service.ValidateAsync(tampered, TokenType.Refresh));
}
[Fact]
public async Task Token_s_alg_none_se_odmitne()
{
static string B64(string s) => Base64UrlEncode(Encoding.UTF8.GetBytes(s));
var unsigned = $"{B64("""{"alg":"none","typ":"refresh+jwt"}""")}.{B64("""{"iss":"https://test","aud":"helpdesk-auth","sub":"1","jti":"x","exp":9999999999}""")}.";
Assert.Null(await _service.ValidateAsync(unsigned, TokenType.Refresh));
}
private static string Base64UrlEncode(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
public class FieldEncryptorTests
{
private readonly FieldEncryptor _encryptor = new(Options.Create(new EncryptionOptions
{
Key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
}));
[Fact]
public void Zasifrovany_telefon_se_desifruje_zpet()
{
var cipher = _encryptor.Encrypt("+420 777 123 456");
Assert.Equal("+420 777 123 456", _encryptor.Decrypt(cipher));
}
[Fact]
public void Stejna_hodnota_dava_pokazde_jiny_sifrovany_text() =>
Assert.NotEqual(_encryptor.Encrypt("123"), _encryptor.Encrypt("123"));
[Fact]
public void Pozmenena_data_se_nedesifruji()
{
var cipher = _encryptor.Encrypt("123");
cipher[^1] ^= 0xFF;
Assert.ThrowsAny<CryptographicException>(() => _encryptor.Decrypt(cipher));
}
[Fact]
public void Kratky_klic_se_odmitne() =>
Assert.Throws<InvalidOperationException>(() =>
new FieldEncryptor(Options.Create(new EncryptionOptions { Key = Convert.ToBase64String(new byte[16]) })));
}
internal sealed class FakeClock(DateTimeOffset now) : TimeProvider
{
private DateTimeOffset _now = now;
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}