backend + web: Add admin account lifecycle management
This commit is contained in:
1 parent
fcf7cd0596
commit
91d0c06c83
25 files changed
+1148
-97
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user