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,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user