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:
1 parent
fc76be7d69
commit
a51d386278
64 files changed
+4394
-1
No files matched your search
@@ -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()))}.");
|
||||
}
|
||||
Reference in new issue
Block a user