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

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

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

No files matched your search

@@ -0,0 +1,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);
}
}