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,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,
}