2026-10-28 21:43:17 +01:00
|
|
|
|
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,
|
|
|
|
|
|
IValidator<RegisterRequest> registerValidator,
|
2026-12-04 20:14:00 +01:00
|
|
|
|
IValidator<ConfirmEmailRequest> confirmEmailValidator,
|
2026-10-28 21:43:17 +01:00
|
|
|
|
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)
|
2026-12-05 02:42:22 +01:00
|
|
|
|
?? throw new FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem.");
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
|
|
|
|
|
var normalized = User.NormalizeEmail(request.Email);
|
2026-11-19 13:41:42 +01:00
|
|
|
|
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
|
|
|
|
|
if (user is null)
|
|
|
|
|
|
{
|
2026-12-04 20:14:00 +01:00
|
|
|
|
user = User.Create(request.Email, "", request.FirstName, request.LastName, role);
|
2026-11-19 13:41:42 +01:00
|
|
|
|
db.Users.Add(user);
|
|
|
|
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
|
|
}
|
2026-12-04 20:14:00 +01:00
|
|
|
|
else if (!user.IsActive || user.EmailConfirmed)
|
2026-11-19 13:41:42 +01:00
|
|
|
|
{
|
2026-10-28 21:43:17 +01:00
|
|
|
|
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
2026-11-19 13:41:42 +01:00
|
|
|
|
}
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await SendEmailConfirmationAsync(user, ct);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
return UserDto.From(user);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
|
|
|
|
|
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
|
|
|
|
|
|
2026-12-04 20:14:00 +01:00
|
|
|
|
public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct)
|
2026-10-28 21:43:17 +01:00
|
|
|
|
{
|
2026-12-04 20:14:00 +01:00
|
|
|
|
await confirmEmailValidator.ValidateAndThrowAsync(request, ct);
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await using var transaction = await db.BeginWriteAsync(ct);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
2026-12-04 21:42:00 +01:00
|
|
|
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
2026-12-04 20:14:00 +01:00
|
|
|
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
2026-10-28 21:43:17 +01:00
|
|
|
|
user.ConfirmEmail();
|
|
|
|
|
|
await db.SaveChangesAsync(ct);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await transaction.CommitAsync(ct);
|
2026-12-04 20:14:00 +01:00
|
|
|
|
revocation.Publish(revoked);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
|
|
|
|
|
{
|
|
|
|
|
|
await loginValidator.ValidateAndThrowAsync(request, ct);
|
|
|
|
|
|
|
|
|
|
|
|
var normalized = User.NormalizeEmail(request.Email);
|
2026-12-04 23:45:00 +01:00
|
|
|
|
var account = await db.Users.Where(u => u.EmailNormalized == normalized && u.IsActive && !u.IsDeleted && u.EmailConfirmed)
|
|
|
|
|
|
.Select(u => new { u.Id, u.EmailNormalized, u.PasswordHash }).SingleOrDefaultAsync(ct);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
|
|
|
|
|
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
2026-12-04 23:45:00 +01:00
|
|
|
|
var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null;
|
|
|
|
|
|
if (!passwordHasher.Verify(request.Password, passwordHash) || account is null)
|
2026-10-28 21:43:17 +01:00
|
|
|
|
throw new UnauthorizedException(invalidCredentials);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
|
2026-12-04 23:45:00 +01:00
|
|
|
|
// Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil.
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await using var transaction = await db.BeginWriteAsync(ct);
|
|
|
|
|
|
var user = await db.LockUserAsync(account.Id, ct);
|
2026-12-04 23:45:00 +01:00
|
|
|
|
if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } ||
|
|
|
|
|
|
user.EmailNormalized != normalized || user.PasswordHash != passwordHash)
|
2026-12-04 17:30:17 +01:00
|
|
|
|
throw new UnauthorizedException(invalidCredentials);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
var response = await IssueTokenPairAsync(user, ct);
|
|
|
|
|
|
await transaction.CommitAsync(ct);
|
|
|
|
|
|
return response;
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <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.");
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
// 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.");
|
2026-12-02 23:18:47 +01:00
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
|
|
|
|
|
{
|
|
|
|
|
|
var response = await IssueTokenPairAsync(user, ct);
|
|
|
|
|
|
await transaction.CommitAsync(ct);
|
|
|
|
|
|
return response;
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-12-04 21:42:00 +01:00
|
|
|
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.ReuseDetected, ct);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await transaction.CommitAsync(ct);
|
|
|
|
|
|
revocation.Publish(revoked);
|
2026-12-02 23:18:47 +01:00
|
|
|
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <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);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-12-04 21:42:00 +01:00
|
|
|
|
public async Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct)
|
|
|
|
|
|
{
|
|
|
|
|
|
var userId = currentUser.Id;
|
|
|
|
|
|
await using var transaction = await db.BeginWriteAsync(ct);
|
|
|
|
|
|
await db.LockUserAsync(userId, ct);
|
|
|
|
|
|
var revoked = await StageDisconnectAsync(userId, RevokeReason.LogoutAll, ct);
|
|
|
|
|
|
await transaction.CommitAsync(ct);
|
|
|
|
|
|
revocation.Publish(revoked);
|
|
|
|
|
|
}
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
|
|
|
|
|
/// <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);
|
2026-11-19 13:41:42 +01:00
|
|
|
|
if (user is null)
|
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
2026-10-28 21:43:17 +01:00
|
|
|
|
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
|
2026-11-19 13:41:42 +01:00
|
|
|
|
}
|
|
|
|
|
|
catch (EmailDeliveryException)
|
|
|
|
|
|
{
|
|
|
|
|
|
// SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná.
|
|
|
|
|
|
}
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
|
|
|
|
|
{
|
|
|
|
|
|
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await using var transaction = await db.BeginWriteAsync(ct);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
2026-12-04 21:42:00 +01:00
|
|
|
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
|
|
|
|
|
await db.SaveChangesAsync(ct);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
await transaction.CommitAsync(ct);
|
|
|
|
|
|
revocation.Publish(revoked);
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-12-04 21:42:00 +01:00
|
|
|
|
// Volat v transakci se zámkem účtu, který používá i registrace zařízení.
|
|
|
|
|
|
private async Task<List<TokenRevocationService.RevokedAccessToken>> StageDisconnectAsync(
|
|
|
|
|
|
int userId, RevokeReason reason, CancellationToken ct)
|
|
|
|
|
|
{
|
|
|
|
|
|
var revoked = await revocation.StageRevokeAllAsync([userId], reason, ct);
|
|
|
|
|
|
await db.PushDevices.Where(device => device.UserId == userId).ExecuteDeleteAsync(ct);
|
|
|
|
|
|
return revoked;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-28 21:43:17 +01:00
|
|
|
|
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));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
2026-10-28 21:43:17 +01:00
|
|
|
|
{
|
2026-12-04 17:30:17 +01:00
|
|
|
|
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);
|
|
|
|
|
|
}
|
2026-10-28 21:43:17 +01:00
|
|
|
|
|
|
|
|
|
|
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
|
|
|
|
|
var (subject, path, text) = type switch
|
|
|
|
|
|
{
|
2026-12-04 20:14:00 +01:00
|
|
|
|
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail a nastavte heslo k účtu"),
|
2026-10-28 21:43:17 +01:00
|
|
|
|
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);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
return true;
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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);
|
2026-12-04 17:30:17 +01:00
|
|
|
|
var user = await db.LockUserAsync(validated.UserId, ct);
|
2026-12-04 20:14:00 +01:00
|
|
|
|
if (user is null || !user.IsActive || (type == TokenType.EmailConfirm && user.EmailConfirmed) ||
|
|
|
|
|
|
!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
2026-10-28 21:43:17 +01:00
|
|
|
|
throw new BadRequestException(invalid);
|
|
|
|
|
|
|
2026-12-04 17:30:17 +01:00
|
|
|
|
return user;
|
2026-10-28 21:43:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|