backend: Add concurrency checks to admin user edits

This commit is contained in:
GonnaHetzMe committed 2026-12-04 18:25:30 +01:00
1 parent 91d0c06c83
commit bd8eb65e56
18 files changed
+216 -23

No files matched your search

@@ -1,9 +1,10 @@
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 class AppException(string message, string? problemType = null) : Exception(message)
{
public abstract int StatusCode { get; }
public string? ProblemType { get; } = problemType;
}
public sealed class NotFoundException(string message) : AppException(message)
@@ -16,6 +17,12 @@ public sealed class ConflictException(string message) : AppException(message)
public override int StatusCode => 409;
}
public sealed class AccountVersionConflictException()
: AppException("Účet se mezitím změnil. Načtěte jeho aktuální údaje a změny zadejte znovu.", "urn:ntbug:account-version-conflict")
{
public override int StatusCode => 409;
}
public sealed class ForbiddenException(string message) : AppException(message)
{
public override int StatusCode => 403;
@@ -1,5 +1,6 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain.Auth;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Notifications;
@@ -14,6 +15,11 @@ public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser
if (user is not { IsActive: true, IsDeleted: false })
throw new UnauthorizedException("Účet není aktivní.");
// Po čekání na zámek mohl správce relaci odhlásit a odstranit všechna její zařízení.
if (!await db.AuthTokens.AnyAsync(t => t.Jti == currentUser.TokenId && t.UserId == user.Id &&
t.TokenType == TokenType.Access && t.RevokedAt == null, ct))
throw new UnauthorizedException("Přihlášení vypršelo. Přihlaste se znovu.");
await db.RegisterPushDeviceAsync(user.Id, token, ct);
await transaction.CommitAsync(ct);
}
@@ -49,14 +49,15 @@ 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)
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
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);
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled, user.RowVersion);
}
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password, int? RowVersion = null);
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
{
@@ -105,12 +105,18 @@ public sealed class UserService(
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
{
if (request.RowVersion is null or < 0)
throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion).");
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 =>
{
if (user.RowVersion != request.RowVersion)
throw new AccountVersionConflictException();
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
var confirmed = !emailChanged && request.EmailConfirmed;
var confirmationChanged = user.EmailConfirmed != confirmed;
@@ -119,12 +125,13 @@ public sealed class UserService(
ApplyProfile(user, request with { EmailConfirmed = confirmed });
sendLink = emailChanged && user.IsActive;
if (passwordHash is not null)
{
user.ChangePasswordHash(passwordHash);
return RevokeReason.PasswordChanged;
}
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;
@@ -186,9 +193,11 @@ public sealed class UserService(
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);
var disconnectedIds = users.Where(user => user.IsDeleted).Select(user => user.Id)
.Concat(changes.Where(change => change.Reason == RevokeReason.PasswordChanged).Select(change => change.Id))
.ToArray();
if (disconnectedIds.Length > 0)
await db.PushDevices.Where(device => disconnectedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);