backend + web: Add admin account lifecycle management

This commit is contained in:
GonnaHetzMe committed 2026-12-04 17:30:17 +01:00
1 parent fcf7cd0596
commit 91d0c06c83
25 files changed
+1148 -97

No files matched your search

@@ -31,6 +31,7 @@ public interface IAppDbContext
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
Task<User?> LockUserAsync(int id, CancellationToken ct);
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
}
@@ -44,29 +44,40 @@ public sealed class AuthService(
throw new ConflictException("Účet s tímto e-mailem už existuje.");
}
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
await SendEmailConfirmationAsync(user, ct);
return UserDto.From(user);
}
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
{
await using var transaction = await db.BeginWriteAsync(ct);
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
user.ConfirmEmail();
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(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);
var account = await db.Users.Where(u => u.EmailNormalized == normalized)
.Select(u => new { u.Id, u.EmailNormalized }).SingleOrDefaultAsync(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)
if (account is null)
throw new UnauthorizedException(invalidCredentials);
await using var transaction = await db.BeginWriteAsync(ct);
var user = await db.LockUserAsync(account.Id, ct);
if (user is null || user.IsDeleted || user.EmailNormalized != account.EmailNormalized)
throw new UnauthorizedException(invalidCredentials);
var now = clock.GetUtcNow().UtcDateTime;
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.");
@@ -74,16 +85,19 @@ public sealed class AuthService(
{
user.RegisterFailedLogin(now);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(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.");
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z ověřovacího e-mailu.");
user.RegisterSuccessfulLogin();
return await IssueTokenPairAsync(user, ct);
var response = await IssueTokenPairAsync(user, ct);
await transaction.CommitAsync(ct);
return response;
}
/// <summary>
@@ -95,22 +109,22 @@ public sealed class AuthService(
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
?? throw new UnauthorizedException("Neplatný refresh token.");
// Původní token zůstane zamčený, dokud není nový pár uložený.
await using (var transaction = await db.BeginWriteAsync(ct))
{
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
{
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.");
// Stejný zámek účtu používá jeho správa, takže během zneplatnění nevznikne nová relace.
await using var transaction = await db.BeginWriteAsync(ct);
var user = await db.LockUserAsync(token.UserId, ct);
if (user is null || !user.IsActive || !user.EmailConfirmed)
throw new UnauthorizedException("Účet neexistuje, je deaktivován nebo nemá ověřený e-mail.");
var response = await IssueTokenPairAsync(user, ct);
await transaction.CommitAsync(ct);
return response;
}
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
{
var response = await IssueTokenPairAsync(user, ct);
await transaction.CommitAsync(ct);
return response;
}
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.ReuseDetected, ct);
await transaction.CommitAsync(ct);
revocation.Publish(revoked);
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
}
@@ -151,12 +165,13 @@ public sealed class AuthService(
{
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
await using var transaction = await db.BeginWriteAsync(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);
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.PasswordChanged, ct);
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
revocation.Publish(revoked);
}
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
@@ -172,21 +187,33 @@ public sealed class AuthService(
UserDto.From(user));
}
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
{
var issued = tokens.Issue(user, type);
db.AuthTokens.Add(issued.Record);
await db.SaveChangesAsync(ct);
IssuedToken issued;
await using (var transaction = await db.BeginWriteAsync(ct))
{
await db.LockUserAsync(user.Id, ct);
var current = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user.Id, ct);
if (current is null || !current.IsActive || current.EmailNormalized != user.EmailNormalized ||
(type == TokenType.EmailConfirm && current.EmailConfirmed))
return false;
issued = tokens.Issue(current, type);
db.AuthTokens.Add(issued.Record);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(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.EmailConfirm => ("Ověření e-mailu", "confirm-email", "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);
return true;
}
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
@@ -194,10 +221,10 @@ public sealed class AuthService(
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))
var user = await db.LockUserAsync(validated.UserId, ct);
if (user is null || !user.IsActive || !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);
return user;
}
}
@@ -31,35 +31,41 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.RevokedAt, now)
.SetProperty(t => t.RevokeReason, reason), ct);
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
Publish(await LoadRevokedAccessTokensAsync([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)
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct) =>
Publish(await StageRevokeAllAsync([userId], reason, ct));
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
{
var now = Now();
await db.AuthTokens
.Where(t => t.UserId == userId && t.RevokedAt == null)
.Where(t => userIds.Contains(t.UserId) && t.RevokedAt == null)
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.RevokedAt, now)
.SetProperty(t => t.RevokeReason, reason), ct);
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
return await LoadRevokedAccessTokensAsync(userIds, 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
private Task<List<RevokedAccessToken>> LoadRevokedAccessTokensAsync(int[] userIds, DateTime revokedAt, CancellationToken ct) =>
db.AuthTokens
.AsNoTracking()
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
.Select(t => new { t.Jti, t.ExpiresAt })
.Where(t => userIds.Contains(t.UserId) && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
.Select(t => new RevokedAccessToken(t.Jti, t.ExpiresAt))
.ToListAsync(ct);
internal void Publish(IEnumerable<RevokedAccessToken> revoked)
{
foreach (var token in revoked)
store.Add(token.Jti, token.ExpiresAt);
}
internal sealed record RevokedAccessToken(string Jti, DateTime 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()
@@ -6,10 +6,16 @@ namespace Helpdesk.Application.Notifications;
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
{
public Task RegisterAsync(string token, CancellationToken ct)
public async Task RegisterAsync(string token, CancellationToken ct)
{
ValidateToken(token);
return db.RegisterPushDeviceAsync(currentUser.Id, token, ct);
await using var transaction = await db.BeginWriteAsync(ct);
var user = await db.LockUserAsync(currentUser.Id, ct);
if (user is not { IsActive: true, IsDeleted: false })
throw new UnauthorizedException("Účet není aktivní.");
await db.RegisterPushDeviceAsync(user.Id, token, ct);
await transaction.CommitAsync(ct);
}
public async Task UnregisterAsync(string token, CancellationToken ct)
@@ -1,4 +1,6 @@
using System.Text;
using FluentValidation;
using Helpdesk.Application.Auth;
using Helpdesk.Domain;
using Helpdesk.Domain.Users;
@@ -45,3 +47,29 @@ public sealed record AdminUserDto(
public sealed record ChangeRoleRequest(string Role);
public sealed record SetActiveRequest(bool IsActive);
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null)
{
public static AdminUserDetailsDto From(User user) => new(user.Id, user.Email, user.FirstName, user.LastName, user.Phone,
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled);
}
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
{
public SaveAdminUserRequestValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
RuleFor(x => x.Role).NotEmpty();
RuleFor(x => x.Password)
.NotEmpty().MinimumLength(PasswordRules.MinLength).MaximumLength(PasswordRules.MaxLength)
.Must(password => password is null || Encoding.UTF8.GetByteCount(password) <= 72)
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.")
.When(x => x.Password is not null);
}
}
public sealed record BulkAdminUsersRequest(int[] UserIds, string Action, string? Role);
@@ -13,7 +13,10 @@ namespace Helpdesk.Application.Users;
public sealed class UserService(
IAppDbContext db,
TokenRevocationService revocation,
IValidator<UpdateProfileRequest> profileValidator)
AuthService auth,
IValidator<UpdateProfileRequest> profileValidator,
IValidator<SaveAdminUserRequest> adminUserValidator,
IPasswordHasher passwordHasher)
{
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
UserDto.From(await GetAsync(currentUser.Id, ct));
@@ -22,9 +25,13 @@ public sealed class UserService(
{
await profileValidator.ValidateAndThrowAsync(request, ct);
var user = await GetAsync(currentUser.Id, ct);
await using var transaction = await db.BeginWriteAsync(ct);
var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id);
if (!user.IsActive)
throw new UnauthorizedException("Účet není aktivní.");
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return UserDto.From(user);
}
@@ -33,7 +40,7 @@ public sealed class UserService(
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 1, 100);
var query = db.Users.AsNoTracking();
var query = db.Users.AsNoTracking().Where(u => !u.IsDeleted);
if (!string.IsNullOrWhiteSpace(q))
{
var term = q.Trim();
@@ -46,9 +53,13 @@ public sealed class UserService(
}
var total = await query.CountAsync(ct);
var offset = (long)(page - 1) * pageSize;
if (offset >= total)
return new PagedResult<AdminUserDto>([], total, page, pageSize);
var users = await query
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
.Skip((page - 1) * pageSize).Take(pageSize)
.Skip((int)offset).Take(pageSize)
.ToListAsync(ct);
var items = users
@@ -58,39 +69,197 @@ public sealed class UserService(
}
/// <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)
public 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);
return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct);
}
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
public Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct) =>
userId == admin.Id && request.IsActive
? Task.CompletedTask
: UpdateAccountsAsync(admin, [userId], user => SetActive(user, request.IsActive), ct);
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
AdminUserDetailsDto.From(await GetAsync(id, ct));
public async Task<AdminUserDetailsDto> CreateAsync(ICurrentUser admin, SaveAdminUserRequest 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);
await ValidateAsync(request, ct);
if (string.IsNullOrWhiteSpace(request.Password))
throw new BadRequestException("Zadejte počáteční heslo.");
var role = ParseRole(request.Role);
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
ApplyProfile(user, request);
user.SetActive(request.IsActive);
await using (var transaction = await db.BeginWriteAsync(ct))
{
RequireAdministrator(await db.LockUserAsync(admin.Id, ct));
db.Users.Add(user);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
return await AccountSavedAsync(user, ct);
}
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
{
await ValidateAsync(request, ct);
var role = ParseRole(request.Role);
var passwordHash = request.Password is null ? null : passwordHasher.Hash(request.Password);
var sendLink = false;
var updated = await UpdateAccountsAsync(admin, [userId], user =>
{
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
var confirmed = !emailChanged && request.EmailConfirmed;
var confirmationChanged = user.EmailConfirmed != confirmed;
var roleChanged = ChangeRole(user, role);
var activeChanged = SetActive(user, request.IsActive);
ApplyProfile(user, request with { EmailConfirmed = confirmed });
sendLink = emailChanged && user.IsActive;
if (passwordHash is not null)
user.ChangePasswordHash(passwordHash);
if (emailChanged || confirmationChanged)
return RevokeReason.LogoutAll;
if (passwordHash is not null)
return RevokeReason.PasswordChanged;
return roleChanged ?? activeChanged;
}, ct);
return sendLink ? await AccountSavedAsync(updated.Single(), ct) : null;
}
public async Task SendEmailConfirmationAsync(int userId, CancellationToken ct)
{
var user = await GetAsync(userId, ct);
if (!user.IsActive || user.EmailConfirmed)
throw new ConflictException("Ověřovací odkaz lze poslat pouze aktivnímu účtu s neověřeným e-mailem.");
if (!await auth.SendEmailConfirmationAsync(user, ct))
throw new ConflictException("Účet se mezitím změnil. Obnovte jeho detail.");
}
public Task DeleteAsync(ICurrentUser admin, int userId, CancellationToken ct) =>
UpdateAccountsAsync(admin, [userId], Delete, ct);
public Task BulkUpdateAsync(ICurrentUser admin, BulkAdminUsersRequest request, CancellationToken ct)
{
if (request.UserIds is not { Length: >= 1 and <= 100 } || request.UserIds.Any(id => id <= 0))
throw new BadRequestException("Vyberte 1 až 100 uživatelů.");
var role = request.Action == "role" ? ParseRole(request.Role ?? "") : default;
return request.Action switch
{
"activate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, true), ct),
"deactivate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, false), ct),
"role" => UpdateAccountsAsync(admin, request.UserIds, user => ChangeRole(user, role), ct),
"delete" => UpdateAccountsAsync(admin, request.UserIds, Delete, ct),
_ => throw new BadRequestException("Vyberte platnou hromadnou akci."),
};
}
private async Task<List<User>> UpdateAccountsAsync(ICurrentUser admin, int[] ids, Func<User, RevokeReason?> update, CancellationToken ct)
{
if (ids.Contains(admin.Id))
throw new ConflictException("Vlastní účet upravujte v nastavení profilu.");
await using var transaction = await db.BeginWriteAsync(ct);
var users = new List<User>();
// Stejné pořadí při překryvu výběrů. Zámek správce brání souběžnému odebrání role.
foreach (var id in ids.Append(admin.Id).Distinct().Order())
{
var user = await db.LockUserAsync(id, ct);
if (id == admin.Id)
RequireAdministrator(user);
else
users.Add(RequireAccount(user, id));
}
var changes = new List<(int Id, RevokeReason Reason)>();
foreach (var user in users)
{
if (update(user) is { } reason)
changes.Add((user.Id, reason));
}
var revoked = new List<TokenRevocationService.RevokedAccessToken>();
foreach (var group in changes.GroupBy(change => change.Reason))
revoked.AddRange(await revocation.StageRevokeAllAsync(group.Select(change => change.Id).ToArray(), group.Key, ct));
var deletedIds = users.Where(user => user.IsDeleted).Select(user => user.Id).ToArray();
if (deletedIds.Length > 0)
await db.PushDevices.Where(device => deletedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
revocation.Publish(revoked);
return users;
}
private async Task<AdminUserDetailsDto> AccountSavedAsync(User user, CancellationToken ct)
{
var result = AdminUserDetailsDto.From(user);
if (!user.IsActive || user.EmailConfirmed)
return result;
try
{
return result with { VerificationEmailSent = await auth.SendEmailConfirmationAsync(user, ct) };
}
catch (EmailDeliveryException)
{
// Účet je již uložený a ověřovací e-mail lze poslat znovu.
return result with { VerificationEmailSent = false };
}
}
private async Task ValidateAsync(SaveAdminUserRequest request, CancellationToken ct)
{
await adminUserValidator.ValidateAndThrowAsync(request, ct);
await profileValidator.ValidateAndThrowAsync(
new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct);
}
private static void ApplyProfile(User user, SaveAdminUserRequest request)
{
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
user.ChangeEmail(request.Email);
user.SetEmailConfirmed(request.EmailConfirmed);
}
private static RevokeReason? ChangeRole(User user, UserRole role)
{
if (user.Role == role)
return null;
user.ChangeRole(role);
return RevokeReason.RoleChanged;
}
private static RevokeReason? SetActive(User user, bool active)
{
var wasActive = user.IsActive;
user.SetActive(active);
return wasActive && !active ? RevokeReason.AccountDeactivated : null;
}
private static RevokeReason? Delete(User user)
{
user.Delete();
return RevokeReason.AccountDeactivated;
}
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.");
RequireAccount(await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct), id);
private static User RequireAccount(User? user, int id) => user is { IsDeleted: false }
? user
: throw new NotFoundException($"Uživatel {id} neexistuje.");
private static void RequireAdministrator(User? user)
{
if (user is not { Role: UserRole.Admin, IsActive: true, IsDeleted: false })
throw new ForbiddenException("K této akci potřebujete aktivní účet administrátora.");
}
private static UserRole ParseRole(string code) =>
EnumCode.TryParse<UserRole>(code, out var role)