Files
NTBug/backend/src/Helpdesk.Application/Auth/TokenRevocationService.cs
T
PatTheEvil a51d386278 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
2026-10-28 21:43:17 +01:00

71 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}