diff --git a/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs b/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs index da9c664..e91ad1b 100644 --- a/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs @@ -27,6 +27,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task> Create(SaveAdminUserRequest request, CancellationToken ct) { var user = await users.CreateAsync(currentUser, request, ct); @@ -36,6 +37,8 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current [HttpPut("{id:int}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] public async Task Update(int id, SaveAdminUserRequest request, CancellationToken ct) { var result = await users.UpdateAsync(currentUser, id, request, ct); @@ -80,6 +83,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current /// Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele. [HttpPut("{id:int}/active")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status409Conflict)] public async Task SetActive(int id, SetActiveRequest request, CancellationToken ct) diff --git a/backend/src/Helpdesk.Api/Controllers/AuthController.cs b/backend/src/Helpdesk.Api/Controllers/AuthController.cs index 2552c93..c70a3f7 100644 --- a/backend/src/Helpdesk.Api/Controllers/AuthController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AuthController.cs @@ -15,8 +15,8 @@ namespace Helpdesk.Api.Controllers; [Produces("application/json")] public sealed class AuthController(AuthService auth) : ControllerBase { - /// Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu. - /// Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit. + /// Registrace e-mailem. Role (student / vyučující) se určí podle domény e-mailu. + /// Heslo se nastavuje až po otevření ověřovacího odkazu z e-mailu. [HttpPost("register")] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -28,11 +28,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase return Created($"/{ApiRoutes.V1}/users/me", user); } - /// Ověření e-mailu tokenem z registračního e-mailu (jednorázový). + /// Ověří e-mail jednorázovým tokenem a nastaví heslo k účtu. [HttpPost("confirm-email")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - public async Task ConfirmEmail(EmailTokenRequest request, CancellationToken ct) + public async Task ConfirmEmail(ConfirmEmailRequest request, CancellationToken ct) { await auth.ConfirmEmailAsync(request, ct); return NoContent(); @@ -42,8 +42,15 @@ public sealed class AuthController(AuthService auth) : ControllerBase [HttpPost("login")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - public Task Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct); + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] + public async Task> Login(LoginRequest request, [FromServices] LoginRateLimiter limiter, CancellationToken ct) + { + if (!limiter.TryAcquire(HttpContext, request.Email)) + return Problem(statusCode: StatusCodes.Status429TooManyRequests, + title: "Příliš mnoho pokusů o přihlášení. Zkuste to za chvíli."); + + return await auth.LoginAsync(request, ct); + } /// Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní. /// Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele. @@ -62,7 +69,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase return NoContent(); } - /// Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele. + /// Odhlášení ze všech zařízení. Zneplatní tokeny a odstraní registrace pro push. [Authorize] [HttpPost("logout-all")] [ProducesResponseType(StatusCodes.Status204NoContent)] diff --git a/backend/src/Helpdesk.Api/Controllers/IssuesController.cs b/backend/src/Helpdesk.Api/Controllers/IssuesController.cs index b256571..f03bf9e 100644 --- a/backend/src/Helpdesk.Api/Controllers/IssuesController.cs +++ b/backend/src/Helpdesk.Api/Controllers/IssuesController.cs @@ -41,6 +41,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase [RequestSizeLimit(AttachmentLimits.MaxRequestBytes)] [RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)] [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] [ProducesResponseType(StatusCodes.Status415UnsupportedMediaType)] [ProducesResponseType(StatusCodes.Status429TooManyRequests)] @@ -55,7 +56,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase var form = await ReadFormAsync(ct); request = new CreateIssueRequest( form["title"].ToString(), form["description"].ToString(), - ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."), + ReadId(form, "categoryId") ?? 0, ReadId(form, "buildingId"), form["locationDetail"].ToString()); uploads = ReadUploads(form.Files); } @@ -87,6 +88,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase } [HttpPut("{id:int}")] + [ProducesResponseType(StatusCodes.Status400BadRequest)] public Task Edit(int id, EditIssueRequest request, CancellationToken ct) => issues.EditAsync(id, request, ct); @@ -160,16 +162,16 @@ public sealed class IssuesController(IssueService issues) : ControllerBase if (string.IsNullOrWhiteSpace(value)) return null; if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id)) - throw new BadRequestException($"Neplatná hodnota {key}."); + throw new FieldValidationException(key, "Zadejte platné ID."); return id; } private static AttachmentUpload[] ReadUploads(IFormFileCollection files) { if (files.Count > AttachmentLimits.MaxFiles) - throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů."); + throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů."); if (files.Any(file => file.Name != "files")) - throw new BadRequestException("Přílohy patří do pole files."); + throw new FieldValidationException("files", "Přílohy patří do pole files."); return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray(); } diff --git a/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs b/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs index bb271d6..e50b91c 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs @@ -20,7 +20,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails) Status = StatusCodes.Status400BadRequest, Title = "Neplatná vstupní data.", }, - AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message }, + AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message, Type = app.ProblemType }, BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode }, _ => null, }; diff --git a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs index 102af77..6bbde59 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs @@ -43,4 +43,10 @@ public static class RateLimitPolicies { public const string Auth = "auth"; public const string IssueWrites = "issue-writes"; + + public static string ClientIp(HttpContext context) + { + var address = context.Connection.RemoteIpAddress; + return (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString() ?? "unknown"; + } } diff --git a/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs b/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs new file mode 100644 index 0000000..464bbc4 --- /dev/null +++ b/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs @@ -0,0 +1,22 @@ +using System.Threading.RateLimiting; +using Helpdesk.Domain.Users; + +namespace Helpdesk.Api.Infrastructure; + +public sealed class LoginRateLimiter : IDisposable +{ + private readonly PartitionedRateLimiter<(string, string)> attempts = + PartitionedRateLimiter.Create<(string, string), (string, string)>(key => + RateLimitPartition.GetFixedWindowLimiter(key, + _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) })); + + public bool TryAcquire(HttpContext context, string? email) + { + var trimmed = email?.Trim(); + var normalized = trimmed is { Length: > 0 and <= 254 } ? User.NormalizeEmail(trimmed) : string.Empty; + using var lease = attempts.AttemptAcquire((RateLimitPolicies.ClientIp(context), normalized)); + return lease.IsAcquired; + } + + public void Dispose() => attempts.Dispose(); +} diff --git a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs index f8991d3..13c13a6 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs @@ -2,6 +2,7 @@ using Microsoft.OpenApi; using Swashbuckle.AspNetCore.SwaggerGen; using Helpdesk.Api.Controllers; using Helpdesk.Application.Issues; +using Helpdesk.Application.Users; namespace Helpdesk.Api.Infrastructure; @@ -34,6 +35,7 @@ public static class SwaggerSetup [new OpenApiSecuritySchemeReference(SchemeId, document)] = [], }); options.OperationFilter(); + options.SchemaFilter(); var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml"); if (File.Exists(xml)) @@ -43,6 +45,30 @@ public static class SwaggerSetup } } +internal sealed class UserStateRequestSchema : ISchemaFilter +{ + public void Apply(IOpenApiSchema schema, SchemaFilterContext context) + { + string[] fields = context.Type switch + { + var type when type == typeof(UpdateProfileRequest) => ["emailNotificationsEnabled"], + var type when type == typeof(SetActiveRequest) => ["isActive"], + var type when type == typeof(SaveAdminUserRequest) => ["isActive", "emailConfirmed", "emailNotificationsEnabled"], + _ => [], + }; + if (fields.Length == 0 || schema is not OpenApiSchema { Properties: { } properties } request) + return; + + request.Required ??= new HashSet(); + foreach (var field in fields) + { + request.Required.Add(field); + if (properties[field] is OpenApiSchema property) + property.Type = JsonSchemaType.Boolean; + } + } +} + internal sealed class IssueRequestBody : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index 96ebe63..e037835 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -49,17 +49,13 @@ if (trustedProxies.Length > 0) } // Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10). +builder.Services.AddSingleton(); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; - options.AddPolicy(RateLimitPolicies.Auth, http => - { - var address = http.Connection.RemoteIpAddress; - if (address is { IsIPv4MappedToIPv6: true }) - address = address.MapToIPv4(); - return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown", - _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }); - }); + options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter( + RateLimitPolicies.ClientIp(http), + _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) })); options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter( http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown", _ => new SlidingWindowRateLimiterOptions diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index 41a2e85..3fffff8 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -39,7 +39,7 @@ public interface IAppDbContext public interface IPasswordHasher { string Hash(string password); - bool Verify(string password, string passwordHash); + bool Verify(string password, string? passwordHash); } /// Vydaný JWT: serializovaný token a záznam pro tabulku auth_token. diff --git a/backend/src/Helpdesk.Application/Auth/AuthDtos.cs b/backend/src/Helpdesk.Application/Auth/AuthDtos.cs index 133653a..9c9efc6 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthDtos.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthDtos.cs @@ -1,17 +1,17 @@ +using System.Text; using FluentValidation; using Helpdesk.Application.Users; namespace Helpdesk.Application.Auth; -public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName); +public sealed record RegisterRequest(string Email, string FirstName, string LastName); public sealed record LoginRequest(string Email, string Password); /// Refresh token – pro /auth/refresh i /auth/logout. public sealed record RefreshTokenRequest(string RefreshToken); -/// Token z odkazu v e-mailu (ověření e-mailu). -public sealed record EmailTokenRequest(string Token); +public sealed record ConfirmEmailRequest(string Token, string NewPassword); public sealed record ForgotPasswordRequest(string Email); @@ -26,11 +26,15 @@ public sealed record AuthResponse( internal static class PasswordRules { - public const int MinLength = 8; - public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů + private const int MinLength = 8; + private const int MaxLength = 64; + private const int MaxUtf8Bytes = 72; - public static IRuleBuilderOptions ValidPassword(this IRuleBuilder rule) => - rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength); + public static IRuleBuilderOptions ValidPassword(this IRuleBuilderInitial rule) => + rule.Cascade(CascadeMode.Stop) + .NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength) + .Must(password => Encoding.UTF8.GetByteCount(password!) <= MaxUtf8Bytes) + .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8."); } public sealed class RegisterRequestValidator : AbstractValidator @@ -38,12 +42,20 @@ public sealed class RegisterRequestValidator : AbstractValidator x.Email).NotEmpty().EmailAddress().MaximumLength(254); - RuleFor(x => x.Password).ValidPassword(); RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100); RuleFor(x => x.LastName).NotEmpty().MaximumLength(100); } } +public sealed class ConfirmEmailRequestValidator : AbstractValidator +{ + public ConfirmEmailRequestValidator() + { + RuleFor(x => x.Token).NotEmpty(); + RuleFor(x => x.NewPassword).ValidPassword(); + } +} + public sealed class LoginRequestValidator : AbstractValidator { public LoginRequestValidator() diff --git a/backend/src/Helpdesk.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index c62f368..c2a5037 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -17,8 +17,8 @@ public sealed class AuthService( TokenRevocationService revocation, IEmailSender emailSender, IOptions registrationOptions, - TimeProvider clock, IValidator registerValidator, + IValidator confirmEmailValidator, IValidator loginValidator, IValidator resetPasswordValidator) { @@ -29,17 +29,17 @@ public sealed class AuthService( await registerValidator.ValidateAndThrowAsync(request, ct); var role = _registration.ResolveRole(request.Email) - ?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem."); + ?? throw new FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem."); var normalized = User.NormalizeEmail(request.Email); var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct); if (user is null) { - user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); + user = User.Create(request.Email, "", request.FirstName, request.LastName, role); db.Users.Add(user); await db.SaveChangesAsync(ct); } - else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash)) + else if (!user.IsActive || user.EmailConfirmed) { throw new ConflictException("Účet s tímto e-mailem už existuje."); } @@ -51,13 +51,18 @@ public sealed class AuthService( internal Task SendEmailConfirmationAsync(User user, CancellationToken ct) => SendEmailTokenAsync(user, TokenType.EmailConfirm, ct); - public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct) + public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct) { + await confirmEmailValidator.ValidateAndThrowAsync(request, ct); + await using var transaction = await db.BeginWriteAsync(ct); var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct); + var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct); + user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword)); user.ConfirmEmail(); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); + revocation.Publish(revoked); } public async Task LoginAsync(LoginRequest request, CancellationToken ct) @@ -65,36 +70,21 @@ public sealed class AuthService( await loginValidator.ValidateAndThrowAsync(request, ct); var normalized = User.NormalizeEmail(request.Email); - var account = await db.Users.Where(u => u.EmailNormalized == normalized) - .Select(u => new { u.Id, u.EmailNormalized }).SingleOrDefaultAsync(ct); + 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); - // 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 (account is null) + var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null; + if (!passwordHasher.Verify(request.Password, passwordHash) || account is null) throw new UnauthorizedException(invalidCredentials); + // Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil. 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) + if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } || + user.EmailNormalized != normalized || user.PasswordHash != passwordHash) 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."); - if (!passwordHasher.Verify(request.Password, user.PasswordHash)) - { - 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 ověřovacího e-mailu."); - - user.RegisterSuccessfulLogin(); var response = await IssueTokenPairAsync(user, ct); await transaction.CommitAsync(ct); return response; @@ -122,7 +112,7 @@ public sealed class AuthService( return response; } - var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.ReuseDetected, ct); + var revoked = await StageDisconnectAsync(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."); @@ -140,8 +130,15 @@ public sealed class AuthService( await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct); } - public Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct) => - revocation.RevokeAllAsync(currentUser.Id, RevokeReason.LogoutAll, ct); + 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); + } /// Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje. public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct) @@ -167,13 +164,22 @@ public sealed class AuthService( await using var transaction = await db.BeginWriteAsync(ct); var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct); - var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.PasswordChanged, ct); + var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct); user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword)); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); revocation.Publish(revoked); } + // Volat v transakci se zámkem účtu, který používá i registrace zařízení. + private async Task> 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; + } + private async Task IssueTokenPairAsync(User user, CancellationToken ct) { var access = tokens.Issue(user, TokenType.Access); @@ -207,7 +213,7 @@ public sealed class AuthService( var baseUrl = _registration.WebBaseUrl.TrimEnd('/'); var (subject, path, text) = type switch { - TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail"), + TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail a nastavte heslo k účtu"), TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"), _ => throw new ArgumentOutOfRangeException(nameof(type)), }; @@ -222,7 +228,8 @@ public sealed class AuthService( var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid); var user = await db.LockUserAsync(validated.UserId, ct); - if (user is null || !user.IsActive || !await revocation.TryConsumeAsync(validated.Jti, type, ct)) + if (user is null || !user.IsActive || (type == TokenType.EmailConfirm && user.EmailConfirmed) || + !await revocation.TryConsumeAsync(validated.Jti, type, ct)) throw new BadRequestException(invalid); return user; diff --git a/backend/src/Helpdesk.Application/Auth/TokenRevocationService.cs b/backend/src/Helpdesk.Application/Auth/TokenRevocationService.cs index 4c70a1a..6efbe41 100644 --- a/backend/src/Helpdesk.Application/Auth/TokenRevocationService.cs +++ b/backend/src/Helpdesk.Application/Auth/TokenRevocationService.cs @@ -34,10 +34,6 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore Publish(await LoadRevokedAccessTokensAsync([userId], now, ct)); } - /// Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1). - public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct) => - Publish(await StageRevokeAllAsync([userId], reason, ct)); - internal async Task> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct) { var now = Now(); diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index 56eaafb..171ca17 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -1,9 +1,13 @@ +using FluentValidation; +using FluentValidation.Results; + namespace Helpdesk.Application.Common; /// Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem. -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) @@ -11,7 +15,13 @@ public sealed class NotFoundException(string message) : AppException(message) public override int StatusCode => 404; } -public sealed class ConflictException(string message) : AppException(message) +public sealed class ConflictException(string message, string? problemType = null) : AppException(message, problemType) +{ + 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; } @@ -31,8 +41,13 @@ public sealed class BadRequestException(string message) : AppException(message) public override int StatusCode => 400; } +public sealed class FieldValidationException(string field, string message) + : ValidationException([new ValidationFailure(field, message)]) +{ +} + public sealed class EmailDeliveryException(string reason, bool retryable) - : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.") + : AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.", "urn:ntbug:email-delivery-failed") { public string Reason { get; } = reason; public bool Retryable { get; } = retryable; diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.cs b/backend/src/Helpdesk.Application/Issues/IssueService.cs index e698694..803f63c 100644 --- a/backend/src/Helpdesk.Application/Issues/IssueService.cs +++ b/backend/src/Helpdesk.Application/Issues/IssueService.cs @@ -1,4 +1,6 @@ using System.Text; +using FluentValidation; +using FluentValidation.Results; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; using Helpdesk.Application.Notifications; @@ -44,11 +46,17 @@ public sealed partial class IssueService( CheckVersion(issue, request.RowVersion); var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct); if (assignee is null || !Issue.CanBeAssigned(assignee.Role)) - throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora."); + throw new FieldValidationException(nameof(request.AssigneeId), "Vyberte aktivního správce budov, člena vedení nebo administrátora."); if (issue.AssigneeId == assignee.Id) throw new ConflictException("Závada je již přiřazena tomuto řešiteli."); - IssuePriority? priority = request.Priority is null ? null : ParseCode(request.Priority); + IssuePriority? priority = null; + if (request.Priority is { } code) + { + if (!EnumCode.TryParse(code, out var selected)) + throw new FieldValidationException(nameof(request.Priority), "Vyberte platnou prioritu."); + priority = selected; + } var from = issue.Status; issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority); AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName); @@ -65,8 +73,8 @@ public sealed partial class IssueService( var (issue, actor) = await LoadActionAsync(id, action, ct); CheckVersion(issue, version); note = action is IssueAction.Reopen or IssueAction.Reject - ? RequiredText(note, "Důvod", MaxTextBytes) - : OptionalText(note, "Poznámka", MaxTextBytes); + ? RequiredText(note, nameof(IssueReasonRequest.Reason), "Důvod") + : OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka"); var from = issue.Status; issue.Transition(action, actor.Id, actor.Role, note); @@ -87,7 +95,7 @@ public sealed partial class IssueService( public async Task CommentAsync(int id, CommentRequest request, CancellationToken ct) { var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct); - var text = RequiredText(request.Text, "Komentář", MaxTextBytes); + var text = RequiredText(request.Text, nameof(request.Text), "Komentář"); issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role); var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text); int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId]; @@ -102,7 +110,7 @@ public sealed partial class IssueService( var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct); var uploads = await readUploads(ct); if (uploads.Length == 0) - throw new BadRequestException("Vyberte alespoň jeden soubor."); + throw new FieldValidationException("files", "Vyberte alespoň jeden soubor."); issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role); var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct); @@ -113,7 +121,7 @@ public sealed partial class IssueService( Issue issue, IReadOnlyList uploads, CancellationToken ct) { if (uploads.Count > AttachmentLimits.MaxFiles) - throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů."); + throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů."); var attachments = new List(uploads.Count); var saving = false; @@ -172,18 +180,31 @@ public sealed partial class IssueService( private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct) { - var title = RequiredText(request.Title, "Název", MaxTextBytes); - RequiredText(request.Description, "Popis", MaxTextBytes); - if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255) - throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků."); + var errors = new List(); + var title = request.Title?.Trim(); + if (string.IsNullOrEmpty(title)) + errors.Add(new(nameof(request.Title), "Zadejte název.")); + else if (title.Length > 200) + errors.Add(new(nameof(request.Title), "Název může mít nejvýše 200 znaků.")); + + var description = request.Description?.Trim(); + if (string.IsNullOrEmpty(description)) + errors.Add(new(nameof(request.Description), "Popište závadu.")); + else if (Encoding.UTF8.GetByteCount(description) > MaxTextBytes) + errors.Add(new(nameof(request.Description), "Popis je příliš dlouhý.")); + if (request.LocationDetail?.Trim().Length > 255) + errors.Add(new(nameof(request.LocationDetail), "Upřesnění místa může mít nejvýše 255 znaků.")); if (original?.CategoryId != request.CategoryId && !await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct)) - throw new BadRequestException("Vyberte aktivní kategorii závady."); + errors.Add(new(nameof(request.CategoryId), "Vyberte aktivní kategorii závady.")); if (request.BuildingId is int buildingId && original?.BuildingId != buildingId && !await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct)) - throw new BadRequestException("Vyberte aktivní budovu."); + errors.Add(new(nameof(request.BuildingId), "Vyberte aktivní budovu.")); + + if (errors.Count > 0) + throw new ValidationException(errors); } private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note) @@ -201,30 +222,33 @@ public sealed partial class IssueService( } catch (DbUpdateConcurrencyException) { - throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav."); + throw IssueVersionConflict(); } } private static void CheckVersion(Issue issue, int? supplied) { if (supplied is null or < 0) - throw new BadRequestException("Zadejte platnou hodnotu rowVersion."); + throw new FieldValidationException(nameof(IssueVersionRequest.RowVersion), "Zadejte platnou verzi závady."); if (issue.RowVersion != supplied) - throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav."); + throw IssueVersionConflict(); } + private static ConflictException IssueVersionConflict() => + new("Závada se mezitím změnila. Načtěte aktuální stav.", "urn:ntbug:issue-version-conflict"); + private const int MaxTextBytes = 65_535; - private static string RequiredText(string? input, string name, int maxBytes) => - OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná."); + private static string RequiredText(string? input, string field, string label) => + OptionalText(input, field, label) ?? throw new FieldValidationException(field, $"{label}: hodnota je povinná."); - private static string? OptionalText(string? input, string name, int maxBytes) + private static string? OptionalText(string? input, string field, string label) { var text = input?.Trim(); if (string.IsNullOrEmpty(text)) return null; - if (Encoding.UTF8.GetByteCount(text) > maxBytes) - throw new BadRequestException($"{name}: hodnota je příliš dlouhá."); + if (Encoding.UTF8.GetByteCount(text) > MaxTextBytes) + throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá."); return text; } diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs index 7299ed3..1847e1f 100644 --- a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs +++ b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs @@ -49,7 +49,7 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs private IQueryable Inbox() { var userId = currentUser.Id; - return db.Notifications.Where(n => n.UserId == userId); + return NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId); } private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationVisibility.cs b/backend/src/Helpdesk.Application/Notifications/NotificationVisibility.cs new file mode 100644 index 0000000..4a1a6af --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationVisibility.cs @@ -0,0 +1,16 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Users; + +namespace Helpdesk.Application.Notifications; + +public static class NotificationVisibility +{ + internal static readonly UserRole[] ReadAllIssueRoles = Enum.GetValues().Where(Issue.CanReadAll).ToArray(); + + public static IQueryable VisibleToRecipients(IAppDbContext db) => + db.Notifications.Where(n => db.Users.Any(u => u.Id == n.UserId && u.IsActive && !u.IsDeleted && + (n.IssueId == null || ReadAllIssueRoles.Contains(u.Role) || + db.Issues.Any(issue => issue.Id == n.IssueId && issue.ReporterId == u.Id)))); +} diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs index 3c9394d..102d3d2 100644 --- a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs +++ b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs @@ -14,9 +14,7 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock) CancellationToken ct) { var reporterId = issue.ReporterId; - var eligibleUsers = db.Users.Where(u => - u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management || - u.Role == UserRole.Admin); + var eligibleUsers = db.Users.Where(u => u.Id == reporterId || NotificationVisibility.ReadAllIssueRoles.Contains(u.Role)); return QueueAsync(eligibleUsers, actorId, recipientIds, id => new Notification(issue, id, type, title, issue.Title), ct); } diff --git a/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs index 0f7b00c..f036d7d 100644 --- a/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs +++ b/backend/src/Helpdesk.Application/Notifications/PushDeviceService.cs @@ -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); } diff --git a/backend/src/Helpdesk.Application/Users/UserDtos.cs b/backend/src/Helpdesk.Application/Users/UserDtos.cs index eadc85a..bccc54e 100644 --- a/backend/src/Helpdesk.Application/Users/UserDtos.cs +++ b/backend/src/Helpdesk.Application/Users/UserDtos.cs @@ -1,4 +1,3 @@ -using System.Text; using FluentValidation; using Helpdesk.Application.Auth; using Helpdesk.Domain; @@ -20,7 +19,7 @@ public sealed record UserDto( user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled); } -public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled); +public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool? EmailNotificationsEnabled); public sealed class UpdateProfileRequestValidator : AbstractValidator { @@ -30,6 +29,7 @@ public sealed class UpdateProfileRequestValidator : AbstractValidator x.LastName).NotEmpty().MaximumLength(100); RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone)) .WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +."); + RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté."); } } @@ -46,17 +46,26 @@ public sealed record AdminUserDto( public sealed record ChangeRoleRequest(string Role); -public sealed record SetActiveRequest(bool IsActive); +public sealed record SetActiveRequest(bool? IsActive); + +public sealed class SetActiveRequestValidator : AbstractValidator +{ + public SetActiveRequestValidator() + { + RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní."); + } +} 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 { @@ -64,11 +73,10 @@ public sealed class SaveAdminUserRequestValidator : AbstractValidator x.Email).NotEmpty().EmailAddress().MaximumLength(254); RuleFor(x => x.Role).NotEmpty(); - RuleFor(x => x.Password) - .NotEmpty().MinimumLength(PasswordRules.MinLength).MaximumLength(PasswordRules.MaxLength) - .Must(password => password is null || Encoding.UTF8.GetByteCount(password) <= 72) - .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.") - .When(x => x.Password is not null); + RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní."); + RuleFor(x => x.EmailConfirmed).NotNull().WithMessage("Uveďte, zda má být e-mail ověřený."); + RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté."); + RuleFor(x => x.Password).ValidPassword().When(x => x.Password is not null); } } diff --git a/backend/src/Helpdesk.Application/Users/UserService.cs b/backend/src/Helpdesk.Application/Users/UserService.cs index 2f1b4a1..4a1a390 100644 --- a/backend/src/Helpdesk.Application/Users/UserService.cs +++ b/backend/src/Helpdesk.Application/Users/UserService.cs @@ -16,6 +16,7 @@ public sealed class UserService( AuthService auth, IValidator profileValidator, IValidator adminUserValidator, + IValidator activeValidator, IPasswordHasher passwordHasher) { public async Task GetMeAsync(ICurrentUser currentUser, CancellationToken ct) => @@ -29,7 +30,7 @@ public sealed class UserService( var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id); if (!user.IsActive) throw new UnauthorizedException("Účet není aktivní."); - user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled); + user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); return UserDto.From(user); @@ -75,10 +76,14 @@ public sealed class UserService( return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct); } - public Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct) => - userId == admin.Id && request.IsActive - ? Task.CompletedTask - : UpdateAccountsAsync(admin, [userId], user => SetActive(user, request.IsActive), ct); + public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct) + { + await activeValidator.ValidateAndThrowAsync(request, ct); + var isActive = request.IsActive!.Value; + if (userId == admin.Id && isActive) + return; + await UpdateAccountsAsync(admin, [userId], user => SetActive(user, isActive), ct); + } public async Task GetAdminAsync(int id, CancellationToken ct) => AdminUserDetailsDto.From(await GetAsync(id, ct)); @@ -86,12 +91,14 @@ public sealed class UserService( public async Task CreateAsync(ICurrentUser admin, SaveAdminUserRequest request, CancellationToken ct) { await ValidateAsync(request, ct); - if (string.IsNullOrWhiteSpace(request.Password)) - throw new BadRequestException("Zadejte počáteční heslo."); + var confirmed = request.EmailConfirmed!.Value; + if (confirmed && string.IsNullOrWhiteSpace(request.Password)) + throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo."); var role = ParseRole(request.Role); - var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role); - ApplyProfile(user, request); - user.SetActive(request.IsActive); + var passwordHash = confirmed ? passwordHasher.Hash(request.Password!) : ""; + var user = User.Create(request.Email, passwordHash, request.FirstName, request.LastName, role); + ApplyProfile(user, request, confirmed); + user.SetActive(request.IsActive!.Value); await using (var transaction = await db.BeginWriteAsync(ct)) { @@ -106,25 +113,34 @@ public sealed class UserService( public async Task UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct) { await ValidateAsync(request, ct); + if (request.RowVersion is null or < 0) + throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion)."); + 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 confirmed = !emailChanged && request.EmailConfirmed!.Value; + if (confirmed && passwordHash is null && user.PasswordHash.Length == 0) + throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo."); var confirmationChanged = user.EmailConfirmed != confirmed; var roleChanged = ChangeRole(user, role); - var activeChanged = SetActive(user, request.IsActive); - ApplyProfile(user, request with { EmailConfirmed = confirmed }); + var activeChanged = SetActive(user, request.IsActive!.Value); + ApplyProfile(user, request, 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 +202,11 @@ public sealed class UserService( var revoked = new List(); 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); @@ -220,11 +238,11 @@ public sealed class UserService( new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct); } - private static void ApplyProfile(User user, SaveAdminUserRequest request) + private static void ApplyProfile(User user, SaveAdminUserRequest request, bool confirmed) { - user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled); + user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value); user.ChangeEmail(request.Email); - user.SetEmailConfirmed(request.EmailConfirmed); + user.SetEmailConfirmed(confirmed); } private static RevokeReason? ChangeRole(User user, UserRole role) diff --git a/backend/src/Helpdesk.Domain/Users/User.cs b/backend/src/Helpdesk.Domain/Users/User.cs index 28dbf13..d51d51b 100644 --- a/backend/src/Helpdesk.Domain/Users/User.cs +++ b/backend/src/Helpdesk.Domain/Users/User.cs @@ -6,9 +6,6 @@ namespace Helpdesk.Domain.Users; /// public sealed class User : IHasCreatedAt { - public const int MaxFailedLogins = 5; - public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15); - private User() { } // EF Core public int Id { get; private set; } @@ -24,8 +21,7 @@ public sealed class User : IHasCreatedAt public bool IsDeleted { get; private set; } public bool EmailConfirmed { get; private set; } public bool EmailNotificationsEnabled { get; private set; } = true; - public int FailedLoginCount { get; private set; } - public DateTime? LockoutUntil { get; private set; } + public int RowVersion { get; private set; } public DateTime CreatedAt { get; set; } public string FullName => $"{FirstName} {LastName}"; @@ -42,25 +38,6 @@ public sealed class User : IHasCreatedAt public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant(); - public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now; - - /// Neúspěšné přihlášení; po pokusech se účet na 15 minut zamkne. - public void RegisterFailedLogin(DateTime now) - { - FailedLoginCount++; - if (FailedLoginCount >= MaxFailedLogins) - { - LockoutUntil = now + LockoutDuration; - FailedLoginCount = 0; - } - } - - public void RegisterSuccessfulLogin() - { - FailedLoginCount = 0; - LockoutUntil = null; - } - public void ConfirmEmail() => EmailConfirmed = true; public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed; @@ -71,11 +48,7 @@ public sealed class User : IHasCreatedAt EmailNormalized = NormalizeEmail(email); } - public void ChangePasswordHash(string passwordHash) - { - PasswordHash = passwordHash; - RegisterSuccessfulLogin(); - } + public void ChangePasswordHash(string passwordHash) => PasswordHash = passwordHash; public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled) { diff --git a/backend/src/Helpdesk.Infrastructure/Background/AttachmentStorageMonitor.cs b/backend/src/Helpdesk.Infrastructure/Background/AttachmentStorageMonitor.cs new file mode 100644 index 0000000..663de48 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Background/AttachmentStorageMonitor.cs @@ -0,0 +1,37 @@ +using Helpdesk.Infrastructure.Files; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Helpdesk.Infrastructure.Background; + +internal sealed partial class AttachmentStorageMonitor(TimeProvider clock, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5), clock); + do + { + try + { + var path = Directory.Exists(FileAttachmentStore.UploadDirectory) + ? FileAttachmentStore.UploadDirectory + : AppContext.BaseDirectory; + var drive = new DriveInfo(path); + var available = drive.AvailableFreeSpace; + if (available < drive.TotalSize / 10) + LogLowSpace(available / (1024 * 1024)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + LogCheckFailed(exception); + } + } + while (await timer.WaitForNextTickAsync(stoppingToken)); + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Na úložišti příloh zbývá méně než 10 % volného místa ({FreeMiB} MiB).")] + private partial void LogLowSpace(long freeMiB); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Volné místo na úložišti příloh se nepodařilo zjistit.")] + private partial void LogCheckFailed(Exception exception); +} diff --git a/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs index e2d072f..ab5978c 100644 --- a/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs +++ b/backend/src/Helpdesk.Infrastructure/Background/NotificationDispatcher.cs @@ -1,6 +1,7 @@ using System.Data; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; using Helpdesk.Domain.Notifications; using Helpdesk.Infrastructure.Email; using Helpdesk.Infrastructure.Notifications; @@ -56,13 +57,13 @@ internal sealed partial class NotificationDispatcher( return false; var recipient = await ( - from notification in db.Notifications.AsNoTracking() + from notification in NotificationVisibility.VisibleToRecipients(db).AsNoTracking() join user in db.Users on notification.UserId equals user.Id where notification.Id == delivery.NotificationId - select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled } - ).SingleAsync(ct); + select new { Notification = notification, user.Id, user.Email, user.EmailConfirmed, user.EmailNotificationsEnabled } + ).SingleOrDefaultAsync(ct); - if (!recipient.IsActive) + if (recipient is null) delivery.Skip(); else if (delivery.Channel == DeliveryChannel.Email) { @@ -73,7 +74,7 @@ internal sealed partial class NotificationDispatcher( } else { - await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct); + await SendPushAsync(db, delivery, recipient.Id, ct); } await db.SaveChangesAsync(ct); @@ -94,8 +95,7 @@ internal sealed partial class NotificationDispatcher( } } - private async Task SendPushAsync( - HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct) + private async Task SendPushAsync(HelpdeskDbContext db, NotificationDelivery delivery, int userId, CancellationToken ct) { var devices = db.PushDevices.Where(d => d.UserId == userId); var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct); @@ -105,7 +105,7 @@ internal sealed partial class NotificationDispatcher( return; } - var result = await push!.SendAsync(notification, tokens, ct); + var result = await push!.SendAsync(tokens, ct); foreach (var invalidToken in result.InvalidTokens) await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct); diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index a9004d0..ba16ac1 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -47,6 +47,7 @@ public static class DependencyInjection services.AddHostedService(); services.AddHostedService(); services.AddHostedService(); + services.AddHostedService(); return services; } diff --git a/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs index eca2958..1419c74 100644 --- a/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs +++ b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs @@ -8,16 +8,16 @@ namespace Helpdesk.Infrastructure.Files; internal sealed class FileAttachmentStore(ILogger logger) : IAttachmentStore { - private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads"); + internal static readonly string UploadDirectory = Path.Combine(AppContext.BaseDirectory, "uploads"); public async Task SaveAsync(AttachmentUpload upload, CancellationToken ct) { if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes) - throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB."); + throw new FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB."); var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim(); if (name.Length is 0 or > 255 || name.Any(char.IsControl)) - throw new BadRequestException("Neplatný název přílohy."); + throw new FieldValidationException("files", "Neplatný název přílohy."); var extension = Path.GetExtension(name).ToLowerInvariant(); var contentType = extension switch @@ -27,10 +27,10 @@ internal sealed class FileAttachmentStore(ILogger logger) : ".heic" => "image/heic", ".pdf" => "application/pdf", ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - _ => throw new BadRequestException("Tento typ přílohy není povolen."), + _ => throw new FieldValidationException("files", "Tento typ přílohy není povolen."), }; - Directory.CreateDirectory(directory); + Directory.CreateDirectory(UploadDirectory); var key = Guid.NewGuid().ToString("D"); var path = FilePath(key); @@ -49,16 +49,16 @@ internal sealed class FileAttachmentStore(ILogger logger) : { written += read; if (written > upload.SizeBytes) - throw new BadRequestException("Velikost přílohy neodpovídá požadavku."); + throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku."); await output.WriteAsync(buffer.AsMemory(0, read), ct); } if (written != upload.SizeBytes) - throw new BadRequestException("Velikost přílohy neodpovídá požadavku."); + throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku."); output.Position = 0; if (!await HasExpectedFormatAsync(output, extension, ct)) - throw new BadRequestException("Obsah přílohy neodpovídá její příponě."); + throw new FieldValidationException("files", "Obsah přílohy neodpovídá její příponě."); return new StoredAttachment(name, key, contentType, written); } @@ -97,7 +97,7 @@ internal sealed class FileAttachmentStore(ILogger logger) : } private string FilePath(string key) => Guid.TryParseExact(key, "D", out _) - ? Path.Combine(directory, key) + ? Path.Combine(UploadDirectory, key) : throw new InvalidOperationException("Neplatný klíč souboru přílohy."); private static async Task HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct) diff --git a/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs index 0821254..7e40290 100644 --- a/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Notifications/FirebasePushSender.cs @@ -1,11 +1,9 @@ -using System.Globalization; using System.Security.Cryptography; using FirebaseAdmin; using FirebaseAdmin.Messaging; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Responses; using Helpdesk.Domain; -using Notification = Helpdesk.Domain.Notifications.Notification; namespace Helpdesk.Infrastructure.Notifications; @@ -37,17 +35,8 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable return new FirebasePushSender(app); } - public async Task SendAsync(Notification notification, string[] tokens, CancellationToken ct) + public async Task SendAsync(string[] tokens, CancellationToken ct) { - var data = new Dictionary - { - ["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture), - }; - if (notification.IssueId is int issueId) - data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture); - if (notification.ProposalId is int proposalId) - data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture); - var messaging = FirebaseMessaging.GetMessaging(app); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(15)); @@ -65,12 +54,11 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable #pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM. Tokens = batch, #pragma warning restore CS0618 - Notification = new FirebaseAdmin.Messaging.Notification + Notification = new Notification { - Title = notification.Title, - Body = notification.Message, + Title = "NTBug", + Body = "V aplikaci máte novou notifikaci.", }, - Data = data, }, timeout.Token); sent |= result.SuccessCount > 0; diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/Configurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/Configurations.cs index 7ba3b64..a192e97 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/Configurations.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/Configurations.cs @@ -16,6 +16,7 @@ internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeC b.Property(u => u.Email).HasMaxLength(254); b.Property(u => u.EmailNormalized).HasMaxLength(254); b.HasIndex(u => u.EmailNormalized).IsUnique(); + b.Property(u => u.RowVersion).IsConcurrencyToken(); b.Property(u => u.Role).HasConversion>().HasMaxLength(30); b.Property(u => u.Phone) .HasColumnName("phone_encrypted") diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 1492c36..ede5122 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -42,6 +42,16 @@ public sealed class HelpdeskDbContext(DbContextOptions option public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State == EntityState.Modified && entry.Properties.Any(property => + property.IsModified && property.Metadata.Name != nameof(User.RowVersion))) + { + var version = entry.Property(user => user.RowVersion); + version.CurrentValue = checked(version.OriginalValue + 1); + } + } + try { return await base.SaveChangesAsync(cancellationToken); @@ -58,6 +68,10 @@ public sealed class HelpdeskDbContext(DbContextOptions option { throw new ConflictException("Účet s tímto e-mailem už existuje."); } + catch (DbUpdateConcurrencyException exception) when (exception.Entries is [var entry] && entry.Entity is User) + { + throw new AccountVersionConflictException(); + } } public Task BeginWriteAsync(CancellationToken ct) => diff --git a/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs b/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs index 9011bc5..a831a43 100644 --- a/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs +++ b/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Helpdesk.Application.Abstractions; namespace Helpdesk.Infrastructure.Security; @@ -6,8 +7,15 @@ namespace Helpdesk.Infrastructure.Security; internal sealed class BCryptPasswordHasher : IPasswordHasher { private const int WorkFactor = 12; + private readonly string dummyHash = BCrypt.Net.BCrypt.HashPassword( + Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), WorkFactor); public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor); - public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash); + public bool Verify(string password, string? passwordHash) + { + var hasPassword = !string.IsNullOrEmpty(passwordHash); + var matches = BCrypt.Net.BCrypt.Verify(password, hasPassword ? passwordHash : dummyHash); + return hasPassword && matches; + } } diff --git a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs index 1b166f6..542edf3 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs @@ -1,13 +1,19 @@ using System.Net; using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Nodes; +using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Common; using Helpdesk.Application.Issues; +using Helpdesk.Application.Notifications; using Helpdesk.Application.Users; using Helpdesk.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.JsonWebTokens; using static Helpdesk.IntegrationTests.BackendFixture; namespace Helpdesk.IntegrationTests; @@ -16,6 +22,51 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF { private const string Users = "/api/v1/admin/users"; + [Fact] + public async Task AdminMustExplicitlySendAccountStateWhenCreatingOrUpdatingAnAccount() + { + using var anonymous = fixture.CreateClient(); + using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); + var request = new SaveAdminUserRequest("explicit-state@example.test", "Test", "Uživatel", null, + "STUDENT", true, true, true, Password); + var body = JsonSerializer.SerializeToNode(request, JsonSerializerOptions.Web)!.AsObject(); + string[] fields = ["isActive", "emailConfirmed", "emailNotificationsEnabled"]; + + foreach (var field in fields) + { + var omitted = body.DeepClone().AsObject(); + omitted.Remove(field); + var validation = await ReadAsync(admin.PostAsJsonAsync(Users, omitted, Cancellation), + HttpStatusCode.BadRequest); + Assert.Equal(field, Assert.Single(validation.Errors.Keys)); + } + + var created = await ReadAsync(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); + var path = $"{Users}/{created.Id}"; + var edit = request with { RowVersion = created.RowVersion, Password = null, FirstName = "Upravené jméno" }; + body = JsonSerializer.SerializeToNode(edit, JsonSerializerOptions.Web)!.AsObject(); + foreach (var field in fields) + { + var omitted = body.DeepClone().AsObject(); + omitted.Remove(field); + var validation = await ReadAsync(admin.PutAsJsonAsync(path, omitted, Cancellation), + HttpStatusCode.BadRequest); + Assert.Equal(field, Assert.Single(validation.Errors.Keys)); + + omitted[field] = null; + validation = await ReadAsync(admin.PutAsJsonAsync(path, omitted, Cancellation), + HttpStatusCode.BadRequest); + Assert.Equal(field, Assert.Single(validation.Errors.Keys)); + } + + Assert.Equal(created, await ReadAsync(admin.GetAsync(path, Cancellation))); + var disabled = edit with { IsActive = false, EmailConfirmed = false, EmailNotificationsEnabled = false }; + await ExpectAsync(admin.PutAsJsonAsync(path, disabled, Cancellation), HttpStatusCode.NoContent); + var saved = await ReadAsync(admin.GetAsync(path, Cancellation)); + Assert.Equal((edit.FirstName, false, false, false), + (saved.FirstName, saved.IsActive, saved.EmailConfirmed, saved.EmailNotificationsEnabled)); + } + [Fact] public async Task AdminCanCreateEditAndAnonymizeAccountsWhileKeepingIssueHistory() { @@ -39,7 +90,11 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF var issue = await ReadAsync(student.PostAsJsonAsync("/api/v1/issues", new CreateIssueRequest("Rozbitý zámek", "Učebnu nelze otevřít.", category.Id, null, null), Cancellation), HttpStatusCode.Created); - var edit = request with { Email = "jana@example.test", FirstName = "Jana", Role = "TEACHER", Password = "New-password-for-test" }; + var edit = request with + { + Email = "jana@example.test", FirstName = "Jana", Role = "TEACHER", + Password = "New-password-for-test", RowVersion = created.RowVersion, + }; var saved = await ReadAsync(admin.PutAsJsonAsync(path, edit, Cancellation)); Assert.False(saved.EmailConfirmed); Assert.True(saved.VerificationEmailSent); @@ -47,8 +102,8 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, Password), Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation), - HttpStatusCode.Forbidden); - await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email)); + HttpStatusCode.Unauthorized); + await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email), password: edit.Password!); var edited = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation)); Assert.Equal((created.Id, edit.Email, edit.FirstName, edit.Role), (edited.User.Id, edited.User.Email, edited.User.FirstName, edited.User.Role)); @@ -89,13 +144,13 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF using var anonymous = fixture.CreateClient(); using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); var request = new SaveAdminUserRequest("needs-confirmation@example.test", "Test", "Uživatel", null, - "STUDENT", true, false, false, Password); + "STUDENT", true, false, false, null); var created = await ReadAsync(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); Assert.True(created.VerificationEmailSent); Assert.False(created.EmailConfirmed); var originalToken = await fixture.TakeConfirmationTokenAsync(request.Email); - var moved = request with { Email = "new-address@example.test", Password = null }; + var moved = request with { Email = "new-address@example.test", Password = null, RowVersion = created.RowVersion }; var updated = await ReadAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", moved, Cancellation)); Assert.True(updated.VerificationEmailSent); await ConfirmEmailAsync(anonymous, originalToken, HttpStatusCode.BadRequest); @@ -112,6 +167,87 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF Assert.Equal(saved.Id, (await LoginAsync(anonymous, retry.Email)).User.Id); } + [Fact] + public async Task StaleAccountEditCannotRestoreAnOldRoleOrReactivateAnAccount() + { + using var anonymous = fixture.CreateClient(); + using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); + var request = new SaveAdminUserRequest("stale-edit@example.test", "Test", "Uživatel", null, + "FACILITY_MANAGER", true, true, false, Password); + var created = await ReadAsync(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); + var path = $"{Users}/{created.Id}"; + var edit = request with { Password = null, Phone = "+420 123 456 789" }; + await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest); + + await ExpectAsync(admin.PutAsJsonAsync(path + "/role", new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent); + var conflict = await ReadAsync( + admin.PutAsJsonAsync(path, edit with { RowVersion = created.RowVersion }, Cancellation), HttpStatusCode.Conflict); + Assert.Equal("urn:ntbug:account-version-conflict", conflict.Type); + var current = await ReadAsync(admin.GetAsync(path, Cancellation)); + Assert.Equal("STUDENT", current.Role); + Assert.Null(current.Phone); + Assert.True(current.RowVersion > created.RowVersion); + + edit = edit with { Role = current.Role, RowVersion = current.RowVersion }; + await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.NoContent); + var refreshed = await ReadAsync(admin.GetAsync(path, Cancellation)); + Assert.Equal(edit.Phone, refreshed.Phone); + + await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk", + new BulkAdminUsersRequest([created.Id], "deactivate", null), Cancellation), HttpStatusCode.NoContent); + await ExpectAsync(admin.PutAsJsonAsync(path, edit with + { + RowVersion = refreshed.RowVersion, Phone = "+420 987 654 321", + }, Cancellation), HttpStatusCode.Conflict); + var deactivated = await ReadAsync(admin.GetAsync(path, Cancellation)); + Assert.False(deactivated.IsActive); + Assert.Equal(edit.Phone, deactivated.Phone); + } + + [Fact] + public async Task AdminPasswordResetDisconnectsDevicesAndRejectsLateRegistrationsFromTheOldSession() + { + using var anonymous = fixture.CreateClient(); + var administrator = await LoginAsync(anonymous, AdminEmail); + using var admin = fixture.CreateClient(administrator.AccessToken); + var request = new SaveAdminUserRequest("password-reset@example.test", "Test", "Účet", null, + "STUDENT", true, true, false, Password); + var newPassword = new string('č', 36); + var tooLong = newPassword + "a"; + var creationError = await ReadAsync(admin.PostAsJsonAsync(Users, + request with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(creationError.Errors["password"])); + var created = await ReadAsync(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); + var originalSession = await LoginAsync(anonymous, created.Email); + using var member = fixture.CreateClient(originalSession.AccessToken); + const string devices = "/api/v1/devices"; + await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.NoContent); + await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-tablet" }, Cancellation), HttpStatusCode.NoContent); + await ExpectAsync(admin.PostAsJsonAsync(devices, new { token = "admin-device" }, Cancellation), HttpStatusCode.NoContent); + + var edit = request with { Password = newPassword, RowVersion = created.RowVersion }; + var editError = await ReadAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", + edit with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(editError.Errors["password"])); + await ExpectAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", edit, Cancellation), HttpStatusCode.NoContent); + await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized); + await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken), + Cancellation), HttpStatusCode.Unauthorized); + + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var oldSession = new CurrentSession(created.Id, new JsonWebToken(originalSession.AccessToken).Id); + await Assert.ThrowsAsync(() => + new PushDeviceService(db, oldSession).RegisterAsync("late-registration", Cancellation)); + Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation)); + Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == administrator.User.Id && device.FcmToken == "admin-device", Cancellation)); + + var newSession = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(created.Email, newPassword), Cancellation)); + using var signedIn = fixture.CreateClient(newSession.AccessToken); + await ExpectAsync(signedIn.PostAsJsonAsync(devices, new { token = "new-phone" }, Cancellation), HttpStatusCode.NoContent); + } + [Fact] public async Task BulkActionsUpdateAllSelectedAccountsAndRejectTheEntireInvalidSelection() { @@ -148,6 +284,9 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF await ExpectAsync(admin.GetAsync($"{Users}/{id}", Cancellation), HttpStatusCode.NotFound); } - private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent) => - ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(token), Cancellation), expected); + private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent, + string password = Password) => + ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new ConfirmEmailRequest(token, password), Cancellation), expected); + + private sealed record CurrentSession(int Id, string TokenId) : ICurrentUser; } diff --git a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs index e47d05d..0082971 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs @@ -68,6 +68,14 @@ public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture< const string profile = "/api/v1/users/me"; const string phone = "+420 123 456 789"; var request = new UpdateProfileRequest("Jana", "Nováková", phone, false); + var missingPreference = await ReadAsync(member.PutAsJsonAsync(profile, + new { request.FirstName, request.LastName, request.Phone }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("emailNotificationsEnabled", missingPreference.Errors.Keys); + var nullPreference = await ReadAsync(member.PutAsJsonAsync(profile, + request with { EmailNotificationsEnabled = null }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("emailNotificationsEnabled", nullPreference.Errors.Keys); + Assert.Equal(user, await ReadAsync(member.GetAsync(profile, Cancellation))); + var validation = await ReadAsync(member.PutAsJsonAsync(profile, request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest); Assert.Contains("phone", validation.Errors.Keys); @@ -88,10 +96,17 @@ public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture< var page = await ReadAsync>(admin.GetAsync(search, Cancellation)); Assert.Equal(user.Id, Assert.Single(page.Items).Id); var activation = $"/api/v1/admin/users/{user.Id}/active"; + var missingState = await ReadAsync(admin.PutAsJsonAsync(activation, + new { }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("isActive", missingState.Errors.Keys); + var nullState = await ReadAsync(admin.PutAsJsonAsync(activation, + new SetActiveRequest(null), Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("isActive", nullState.Errors.Keys); + Assert.Equal(updated, await ReadAsync(member.GetAsync(profile, Cancellation))); await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation), - HttpStatusCode.Forbidden); + HttpStatusCode.Unauthorized); await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent); Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id); } diff --git a/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs index c6358f6..a8cb7ee 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs @@ -5,6 +5,7 @@ using System.Net.Http.Json; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; using Helpdesk.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using static Helpdesk.IntegrationTests.BackendFixture; @@ -49,7 +50,8 @@ public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest); + Assert.Equal("files", Assert.Single(validation.Errors.Keys)); using var wrongField = new MultipartFormDataContent(); wrongField.Add(new ByteArrayContent(png), "image", "zamek.png"); diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs index 4937a4f..1be2be0 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs @@ -1,8 +1,11 @@ using System.Net; using System.Net.Http.Json; +using Helpdesk.Api.Controllers; +using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Domain.Auth; using Helpdesk.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.JsonWebTokens; @@ -13,24 +16,66 @@ namespace Helpdesk.IntegrationTests; public sealed class AuthTests(BackendFixture fixture) : IClassFixture { [Fact] - public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession() + public async Task LoginFailuresAreGenericAndLoginLimitAppliesPerClientAndEmail() + { + using var setup = fixture.CreateClient(); + var user = await fixture.RegisterAsync(setup); + var unrelated = await fixture.RegisterAsync(setup); + using var limitedClient = fixture.CreateClient(); + using var otherClient = fixture.CreateClient(); + const string login = "/api/v1/auth/login"; + const string wrongPassword = "Wrong-integration-password"; + var unknown = await ReadAsync(limitedClient.PostAsJsonAsync(login, + new LoginRequest("unknown@example.test", wrongPassword), Cancellation), HttpStatusCode.Unauthorized); + + for (var attempt = 0; attempt < 5; attempt++) + { + var failure = await ReadAsync(limitedClient.PostAsJsonAsync(login, + new LoginRequest($" {user.Email.ToUpperInvariant()} ", wrongPassword), Cancellation), HttpStatusCode.Unauthorized); + Assert.Equal((unknown.Status, unknown.Title, unknown.Type), (failure.Status, failure.Title, failure.Type)); + } + + await ExpectAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest(user.Email, Password), Cancellation), + HttpStatusCode.TooManyRequests); + Assert.Equal(unrelated.Id, (await LoginAsync(limitedClient, unrelated.Email)).User.Id); + Assert.Equal(user.Id, (await LoginAsync(otherClient, user.Email)).User.Id); + } + + [Fact] + public async Task ResetReplacesALegacyPasswordAndRevokesTheOldSessionAndDevice() { using var anonymous = fixture.CreateClient(); var user = await fixture.RegisterAsync(anonymous); - using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken); + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var hasher = scope.ServiceProvider.GetRequiredService(); + var legacyPassword = new string('ž', 37); + var account = await db.Users.SingleAsync(u => u.Id == user.Id, Cancellation); + account.ChangePasswordHash(hasher.Hash(legacyPassword)); + await db.SaveChangesAsync(Cancellation); + + var oldLogin = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(user.Email, legacyPassword), Cancellation)); + using var oldSession = fixture.CreateClient(oldLogin.AccessToken); + await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices", + new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password", new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent); - const string newPassword = "New-integration-password"; + var newPassword = new string('č', 36); var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword); + var validation = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", + reset with { NewPassword = newPassword + "a" }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"])); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest); await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", - new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized); + new LoginRequest(user.Email, legacyPassword), Cancellation), HttpStatusCode.Unauthorized); var session = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, newPassword), Cancellation)); Assert.Equal(user.Id, session.User.Id); + Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); } [Fact] @@ -57,6 +102,29 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture(); + Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); + Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == otherUser.Id, Cancellation)); + } + [Fact] public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions() { @@ -64,6 +132,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture(first); await ExpectAsync(duplicate, HttpStatusCode.Unauthorized); await using var after = fixture.Services.CreateAsyncScope(); - var tokens = after.ServiceProvider.GetRequiredService().AuthTokens; - Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation)); + var afterDb = after.ServiceProvider.GetRequiredService(); + Assert.False(await afterDb.AuthTokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation)); + Assert.False(await afterDb.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); using var renewedClient = fixture.CreateClient(renewed.AccessToken); - using var otherClient = fixture.CreateClient(otherSession.AccessToken); await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); } diff --git a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs index 521a837..f5a4105 100644 --- a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs +++ b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs @@ -36,6 +36,7 @@ public sealed class BackendFixture : IAsyncLifetime .Build(); private readonly TestEmailSender email = new(); private ApiFactory? factory; + private int clientNumber; internal TokenSaveGate TokenSaves { get; } = new(); internal IServiceProvider Services => factory!.Services; @@ -62,7 +63,13 @@ public sealed class BackendFixture : IAsyncLifetime internal HttpClient CreateClient(string? accessToken = null) { - var client = factory!.CreateClient(); + // Každý klient simuluje vlastní IP adresu a má vlastní limit požadavků na přihlášení. + var address = IPAddress.Parse($"2001:db8::{Interlocked.Increment(ref clientNumber):x}"); + var server = factory!.Server; + var client = new HttpClient(server.CreateHandler(context => context.Connection.RemoteIpAddress = address)) + { + BaseAddress = server.BaseAddress, + }; if (accessToken is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return client; @@ -75,9 +82,9 @@ public sealed class BackendFixture : IAsyncLifetime { var address = $"{Guid.NewGuid():N}@student.example.test"; var user = await ReadAsync(client.PostAsJsonAsync("/api/v1/auth/register", - new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created); + new RegisterRequest(address, "Test", "User"), Cancellation), HttpStatusCode.Created); await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", - new EmailTokenRequest(await TakeConfirmationTokenAsync(address)), Cancellation), HttpStatusCode.NoContent); + new ConfirmEmailRequest(await TakeConfirmationTokenAsync(address), Password), Cancellation), HttpStatusCode.NoContent); return user; } diff --git a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs index 22acd29..e0950d5 100644 --- a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs @@ -68,6 +68,21 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture property.GetString() == field); + Assert.Equal("boolean", properties.GetProperty(field).GetProperty("type").GetString()); + } } [Fact] diff --git a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs new file mode 100644 index 0000000..28c0fd4 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs @@ -0,0 +1,105 @@ +using System.Net; +using System.Net.Http.Json; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Auth; +using Helpdesk.Application.Users; +using Helpdesk.Domain.Auth; +using Helpdesk.Domain.Users; +using Helpdesk.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using static Helpdesk.IntegrationTests.BackendFixture; + +namespace Helpdesk.IntegrationTests; + +public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixture +{ + private const string Register = "/api/v1/auth/register"; + private const string Confirm = "/api/v1/auth/confirm-email"; + private const string Login = "/api/v1/auth/login"; + + [Fact] + public async Task FailedRegistrationEmailCanBeRetriedForTheSameAccount() + { + using var anonymous = fixture.CreateClient(); + const string address = "retry@student.example.test"; + var request = new RegisterRequest(address, "Jan", "Novák"); + fixture.FailNextEmail(address, "SMTP_UNAVAILABLE", retryable: true); + + var failure = await ReadAsync(anonymous.PostAsJsonAsync(Register, request, Cancellation), + HttpStatusCode.ServiceUnavailable); + Assert.Equal("urn:ntbug:email-delivery-failed", failure.Type); + + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var pending = await db.Users.AsNoTracking().SingleAsync(user => user.Email == address, Cancellation); + Assert.False(pending.EmailConfirmed); + Assert.Empty(pending.PasswordHash); + + var retried = await ReadAsync(anonymous.PostAsJsonAsync(Register, request, Cancellation), HttpStatusCode.Created); + Assert.Equal(pending.Id, retried.Id); + var token = await fixture.TakeConfirmationTokenAsync(address); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation), + HttpStatusCode.NoContent); + Assert.Equal(pending.Id, (await LoginAsync(anonymous, address)).User.Id); + } + + [Fact] + public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt() + { + using var anonymous = fixture.CreateClient(); + const string address = "new@student.example.test"; + var user = await ReadAsync(anonymous.PostAsJsonAsync(Register, + new RegisterRequest(address, "Jan", "Novák"), Cancellation), HttpStatusCode.Created); + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var pending = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user.Id, Cancellation); + Assert.False(pending.EmailConfirmed); + Assert.Empty(pending.PasswordHash); + await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, Password), Cancellation), + HttpStatusCode.Unauthorized); + + var token = await fixture.TakeConfirmationTokenAsync(address); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation), + HttpStatusCode.NoContent); + Assert.Equal(user.Id, (await LoginAsync(anonymous, address)).User.Id); + } + + [Fact] + public async Task AnExistingConfirmationLinkRequiresANewPasswordAndCanOnlyBeUsedOnce() + { + using var anonymous = fixture.CreateClient(); + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var hasher = scope.ServiceProvider.GetRequiredService(); + const string address = "legacy@student.example.test"; + const string oldPassword = "Legacy-unconfirmed-password"; + var pending = User.Create(address, hasher.Hash(oldPassword), "Eva", "Nováková", UserRole.Student); + db.Users.Add(pending); + await db.SaveChangesAsync(Cancellation); + var original = scope.ServiceProvider.GetRequiredService().Issue(pending, TokenType.EmailConfirm); + db.AuthTokens.Add(original.Record); + await db.SaveChangesAsync(Cancellation); + await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation), + HttpStatusCode.Unauthorized); + + await ExpectAsync(anonymous.PostAsJsonAsync(Register, new RegisterRequest(address, "Jiné", "Jméno"), Cancellation), + HttpStatusCode.Created); + var otherToken = await fixture.TakeConfirmationTokenAsync(address); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation), + HttpStatusCode.BadRequest); + var newPassword = new string('č', 36); + var validation = await ReadAsync(anonymous.PostAsJsonAsync(Confirm, + new ConfirmEmailRequest(original.Token, newPassword + "a"), Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"])); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, newPassword), Cancellation), + HttpStatusCode.NoContent); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation), + HttpStatusCode.BadRequest); + await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation), + HttpStatusCode.Unauthorized); + var session = await ReadAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, newPassword), Cancellation)); + Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName)); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs index fd79a14..c122f91 100644 --- a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs @@ -5,12 +5,46 @@ using Helpdesk.Application.Common; using Helpdesk.Application.Issues; using Helpdesk.Application.Notifications; using Helpdesk.Application.Statistics; +using Microsoft.AspNetCore.Mvc; using static Helpdesk.IntegrationTests.BackendFixture; namespace Helpdesk.IntegrationTests; public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture { + [Fact] + public async Task IssueValidationReturnsErrorsWithFieldNames() + { + using var anonymous = fixture.CreateClient(); + var administrator = await LoginAsync(anonymous, AdminEmail); + using var admin = fixture.CreateClient(administrator.AccessToken); + const string issues = "/api/v1/issues"; + var invalid = new CreateIssueRequest(new string('t', 201), " ", int.MaxValue, int.MaxValue, new string('l', 256)); + + var creationError = await ReadAsync(admin.PostAsJsonAsync(issues, invalid, Cancellation), + HttpStatusCode.BadRequest); + Assert.Equal(["buildingId", "categoryId", "description", "locationDetail", "title"], creationError.Errors.Keys.Order()); + + using var form = new MultipartFormDataContent { { new StringContent("invalid"), "categoryId" } }; + var uploadError = await ReadAsync(admin.PostAsync(issues, form, Cancellation), HttpStatusCode.BadRequest); + Assert.Equal("categoryId", Assert.Single(uploadError.Errors.Keys)); + + var categories = await ReadAsync(admin.GetAsync("/api/v1/issue-categories", Cancellation)); + var issue = await PostIssueAsync(admin, issues, new CreateIssueRequest("Projektor", "Bliká.", categories[0].Id, null, null), + HttpStatusCode.Created); + var path = $"{issues}/{issue.Id}"; + var edit = new EditIssueRequest(issue.Title, issue.Description, int.MaxValue, null, null, issue.RowVersion); + var editError = await ReadAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest); + Assert.Equal("categoryId", Assert.Single(editError.Errors.Keys)); + + var assign = new AssignIssueRequest(administrator.User.Id, "UNKNOWN", issue.RowVersion); + var priorityError = await ReadAsync(admin.PostAsJsonAsync(path + "/assign", assign, Cancellation), + HttpStatusCode.BadRequest); + Assert.Equal("priority", Assert.Single(priorityError.Errors.Keys)); + var saved = await ReadAsync(admin.GetAsync(path, Cancellation)); + Assert.Equal((issue.RowVersion, issue.CategoryId, issue.AssigneeId), (saved.RowVersion, saved.CategoryId, saved.AssigneeId)); + } + [Fact] public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt() { @@ -52,8 +86,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture(admin.GetAsync("/api/v1/users/assignable", Cancellation)); Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id); Assert.Contains(assignable, user => user.Id == administrator.User.Id); - await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start", + var conflict = await ReadAsync(firstSolver.PostAsJsonAsync(path + "/start", new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict); + Assert.Equal("urn:ntbug:issue-version-conflict", conflict.Type); var reporterNotifications = await InboxAsync(reporter, issue.Id); Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type); diff --git a/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs index e671f5e..7a4b75d 100644 --- a/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs @@ -5,6 +5,7 @@ using Helpdesk.Application.Catalogs; using Helpdesk.Application.Common; using Helpdesk.Application.Issues; using Helpdesk.Application.Notifications; +using Helpdesk.Application.Users; using Helpdesk.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -66,6 +67,50 @@ public sealed class NotificationTests(BackendFixture fixture) : IClassFixture>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items); } + [Fact] + public async Task RoleChangeHidesOtherIssuesAndSkipsQueuedEmail() + { + using var anonymous = fixture.CreateClient(); + using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); + var reporterAccount = await fixture.RegisterAsync(anonymous); + using var reporter = fixture.CreateClient((await LoginAsync(anonymous, reporterAccount.Email)).AccessToken); + var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT"); + using var manager = fixture.CreateClient(managerSession.AccessToken); + const string issues = "/api/v1/issues"; + const string inbox = "/api/v1/notifications"; + var categories = await ReadAsync(reporter.GetAsync("/api/v1/issue-categories", Cancellation)); + var request = new CreateIssueRequest("Závada v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null); + + fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false); + var issue = await ReadAsync(reporter.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created); + var before = await ReadAsync>(manager.GetAsync(inbox, Cancellation)); + var hidden = Assert.Single(before.Items); + Assert.Equal(issue.Id, hidden.IssueId); + var failed = await WaitForDeliveryAsync(admin, hidden.Id, "FAILED"); + + await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{managerSession.User.Id}/role", + new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent); + using var student = fixture.CreateClient((await LoginAsync(anonymous, managerSession.User.Email)).AccessToken); + var ownIssue = await ReadAsync(student.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created); + await ReadAsync(admin.PostAsJsonAsync($"{issues}/{ownIssue.Id}/comments", + new CommentRequest("Komentář k vlastní závadě uživatele."), Cancellation)); + + var after = await ReadAsync>(student.GetAsync(inbox, Cancellation)); + Assert.Equal(1, after.TotalCount); + Assert.Equal(ownIssue.Id, Assert.Single(after.Items).IssueId); + Assert.Equal(1, (await ReadAsync(student.GetAsync(inbox + "/unread-count", Cancellation))).Count); + await ExpectAsync(student.PostAsync($"{inbox}/{hidden.Id}/read", null, Cancellation), HttpStatusCode.NotFound); + await ExpectAsync(student.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent); + Assert.Equal(0, (await ReadAsync(student.GetAsync(inbox + "/unread-count", Cancellation))).Count); + + await ExpectAsync(admin.PostAsync($"/api/v1/admin/notification-deliveries/{failed.Id}/retry", null, Cancellation), + HttpStatusCode.NoContent); + await WaitForDeliveryAsync(admin, hidden.Id, "SKIPPED", attempts: 0); + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Null(await db.Notifications.Where(n => n.Id == hidden.Id).Select(n => n.ReadAt).SingleAsync(Cancellation)); + } + [Fact] public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership() { diff --git a/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs index 84d5292..9303395 100644 --- a/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs @@ -1,4 +1,6 @@ using System.Net; +using System.Text.Json; +using Helpdesk.Application.Auth; using Microsoft.AspNetCore.TestHost; using static Helpdesk.IntegrationTests.BackendFixture; @@ -16,16 +18,16 @@ public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture< await using var api = fixture.CreateApiBehindProxies(externalProxy, web); for (var attempt = 0; attempt < 20; attempt++) - Assert.Equal(401, await LoginAsync(api.Server, web, firstClient)); + Assert.Equal(401, await LoginAsync(api.Server, web, firstClient, $"absent-{attempt}@example.test")); - Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient)); - Assert.Equal(401, await LoginAsync(api.Server, web, secondClient)); - Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient)); + Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient, "absent@example.test")); + Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "absent@example.test")); + Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "absent@example.test")); } - private static async Task LoginAsync(TestServer server, string peer, string client) + private static async Task LoginAsync(TestServer server, string peer, string client, string email) { - using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray()); + using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(new LoginRequest(email, "test-password"))); var response = await server.SendAsync(context => { context.Connection.RemoteIpAddress = IPAddress.Parse(peer); diff --git a/backend/tests/Helpdesk.UnitTests/DomainTests.cs b/backend/tests/Helpdesk.UnitTests/DomainTests.cs index 48f8789..30a9fbc 100644 --- a/backend/tests/Helpdesk.UnitTests/DomainTests.cs +++ b/backend/tests/Helpdesk.UnitTests/DomainTests.cs @@ -37,46 +37,11 @@ public class EnumCodeTests public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse("SUPERUSER", out _)); } -public class UserLockoutTests +public class UserTests { - private static readonly DateTime Now = new(2026, 10, 29, 10, 0, 0, DateTimeKind.Utc); - - private static User NewUser() => User.Create("jan@student.univerzita.cz", "hash", "Jan", "Novák", UserRole.Student); - - [Fact] - public void Ctyri_neuspesne_pokusy_ucet_nezamknou() - { - var user = NewUser(); - for (var i = 0; i < User.MaxFailedLogins - 1; i++) - user.RegisterFailedLogin(Now); - - Assert.False(user.IsLockedOut(Now)); - } - - [Fact] - public void Paty_neuspesny_pokus_zamkne_ucet_na_15_minut() - { - var user = NewUser(); - for (var i = 0; i < User.MaxFailedLogins; i++) - user.RegisterFailedLogin(Now); - - Assert.True(user.IsLockedOut(Now.AddMinutes(14))); - Assert.False(user.IsLockedOut(Now.AddMinutes(15))); - } - - [Fact] - public void Uspesne_prihlaseni_vynuluje_pocitadlo() - { - var user = NewUser(); - user.RegisterFailedLogin(Now); - user.RegisterSuccessfulLogin(); - - Assert.Equal(0, user.FailedLoginCount); - } - [Fact] public void Email_se_normalizuje_pro_jednoznacne_vyhledani() => - Assert.Equal("JAN@STUDENT.UNIVERZITA.CZ", NewUser().EmailNormalized); + Assert.Equal("JAN@STUDENT.UNIVERZITA.CZ", User.Create("jan@student.univerzita.cz", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized); } public class RegistrationRoleTests diff --git a/db/migrations/V006__user_row_version.sql b/db/migrations/V006__user_row_version.sql new file mode 100644 index 0000000..9e72231 --- /dev/null +++ b/db/migrations/V006__user_row_version.sql @@ -0,0 +1,2 @@ +ALTER TABLE app_user + ADD COLUMN row_version INT NOT NULL DEFAULT 0; diff --git a/db/migrations/V007__remove_unused_login_lockout_columns.sql b/db/migrations/V007__remove_unused_login_lockout_columns.sql new file mode 100644 index 0000000..c3d4057 --- /dev/null +++ b/db/migrations/V007__remove_unused_login_lockout_columns.sql @@ -0,0 +1,3 @@ +ALTER TABLE app_user + DROP COLUMN IF EXISTS failed_login_count, + DROP COLUMN IF EXISTS lockout_until; diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 04c935d..9f1c25d 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -113,7 +113,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr ### Účty a přístup | ID | Požadavek | |---|---| -| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. | +| FR-01 | Registrace univerzitním e-mailem. Příjemce ověří e-mail a nastaví heslo přes jednorázový odkaz. | | FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. | | FR-03 | Obnova zapomenutého hesla přes e-mail. | | FR-04 | Administrátor vyhledává, zakládá a upravuje účty, mění role, aktivuje, deaktivuje a maže účty. Role, stav i smazání může změnit u více účtů najednou. | @@ -374,9 +374,10 @@ sequenceDiagram end ``` -- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky). +- **V aplikaci:** notifikace se uloží do tabulky `notification` ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky). - **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit. -- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`); backend odesílá přes Firebase Admin SDK. +- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`). Backend přes Firebase Admin SDK posílá obecné upozornění. Podrobnosti klient načte z API po přihlášení. +- Při zobrazení notifikace v aplikaci i před doručením e-mailu nebo push backend ověřuje aktuální přístup příjemce k související závadě. - Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel. ### 8.3 Řešení nedoručení @@ -470,7 +471,7 @@ Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "C | Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku | | Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore | | Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním | -| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), deep link na detail závady | +| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), podrobnosti v přihlášené aplikaci | | Min. verze | Android 8.0 (API 26) | ### 9.6 Struktura repozitáře (Git, EngineRevive) @@ -510,11 +511,11 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/`, merg | Oblast | Řešení | |---|---| -| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. | -| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/v1/auth/*`. | +| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Nové heslo má 8–64 znaků a nejvýše 72 bajtů v UTF-8. | +| Přihlášení | Neúspěšné ověření vrací jednotnou odpověď, BCrypt se provádí i pro neznámý účet. Každá instance API omezuje přihlášení na 5 pokusů za minutu pro dvojici klientská IP a normalizovaný e-mail. Pro `/api/v1/auth/*` platí také limit 20 požadavků za minutu na klientskou IP. | | Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). | | Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. | -| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. | +| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. Web nabízí PDF ke stažení. API zapisuje varování do logu, pokud na svazku s přílohami zbývá méně než 10 % volného místa. | | Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. | | Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). | | Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. | @@ -655,8 +656,8 @@ Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/ ### Autentizace a účet | Metoda | Endpoint | Role | Popis | |---|---|---|---| -| POST | `/auth/register` | anonym | Registrace (e-mail, heslo, jméno, příjmení) | -| POST | `/auth/confirm-email` | anonym | Ověření e-mailu tokenem | +| POST | `/auth/register` | anonym | Registrace (e-mail, jméno, příjmení) a odeslání ověřovacího odkazu. Po `503` s typem `urn:ntbug:email-delivery-failed` lze stejným požadavkem zopakovat odeslání pro uložený účet. | +| POST | `/auth/confirm-email` | anonym | Ověření e-mailu a nastavení hesla v jedné transakci (`{ token, newPassword }`) | | POST | `/auth/login` | anonym | Vrací `accessToken`, `refreshToken`, údaje uživatele a roli | | POST | `/auth/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) | | POST | `/auth/logout` | přihlášený | Zablokuje `jti` access i refresh tokenu | @@ -724,8 +725,8 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal | GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře | | POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) | | GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů | -| POST | `/admin/users` | admin | Založení účtu s počátečním heslem a ručním nebo e-mailovým ověřením | -| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu, nové heslo je volitelné. Změna adresy aktivního účtu spustí nové ověření. | +| POST | `/admin/users` | admin | Založení účtu s ručním ověřením a počátečním heslem, nebo s odkazem pro nastavení hesla příjemcem | +| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu s `rowVersion`. Zastaralá verze vrátí 409. Změna adresy aktivního účtu spustí nové ověření. Nové heslo odhlásí relace a odpojí push zařízení. | | POST | `/admin/users/{id}/email-confirmation` | admin | Opětovné odeslání odkazu aktivnímu účtu s neověřeným e-mailem | | DELETE | `/admin/users/{id}` | admin | Znepřístupnění účtu a anonymizace profilu | | POST | `/admin/users/bulk` | admin | Změna role, aktivace, deaktivace nebo smazání vybraných účtů v jedné transakci | @@ -779,8 +780,6 @@ erDiagram bool is_active bool email_confirmed bool email_notifications_enabled - int failed_login_count - datetime lockout_until datetime created_at } auth_token { @@ -950,7 +949,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích - Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index. - Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`. - Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky. -- Zůstávají jen **funkční časy**, které popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu), `app_user.lockout_until`. +- **Funkční časy** popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu). - *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit. - `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`. @@ -985,7 +984,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích - **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion()`. - **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh. - **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov, vedení nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa. -- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token). +- **Optimistické zamykání**: `issue.row_version` a `app_user.row_version` (EF Core concurrency token). - **Mazání účtů**: smazaný účet se deaktivuje, jeho profil se anonymizuje a účet se skryje ze správy uživatelů (`is_deleted`). Původní e-mail je volný pro nový účet. Vazby závad, návrhů, hlasů a událostí zůstanou v databázi. Číselníky se deaktivují (`is_active`), závady a návrhy zůstávají v historii. - **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient. - **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče). diff --git a/web/Helpdesk.Web.Tests/AdminUsersTests.cs b/web/Helpdesk.Web.Tests/AdminUsersTests.cs index 6002516..f1472f2 100644 --- a/web/Helpdesk.Web.Tests/AdminUsersTests.cs +++ b/web/Helpdesk.Web.Tests/AdminUsersTests.cs @@ -1,6 +1,5 @@ using System.Net; using System.Text; -using System.Text.RegularExpressions; using Helpdesk.Web.Api; using Helpdesk.Web.Auth; using Microsoft.AspNetCore.Mvc.Testing; @@ -151,13 +150,17 @@ public sealed class AdminUsersTests using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct); Assert.Equal(HttpStatusCode.OK, editPage.StatusCode); - Assert.Contains("novak@example.test", await editPage.Content.ReadAsStringAsync(ct)); + var editHtml = await editPage.Content.ReadAsStringAsync(ct); + Assert.Contains("novak@example.test", editHtml); + Assert.Matches("""]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", editHtml); fields.Remove("Password"); + fields["RowVersion"] = "3"; using var editForm = new FormUrlEncodedContent(fields); using var edited = await client.PostAsync(UsersPath + "/7/edit", editForm, ct); Assert.Equal(HttpStatusCode.Redirect, edited.StatusCode); Assert.Equal(HttpMethod.Put, backend.Requests[^1].Method); Assert.Contains("\"password\":null", backend.Requests[^1].Body); + Assert.Contains("\"rowVersion\":3", backend.Requests[^1].Body); var bulk = new List> { @@ -209,7 +212,6 @@ public sealed class AdminUsersTests ["LastName"] = "Novák", ["Email"] = "novak@example.test", ["Role"] = UserRoles.Student, - ["Password"] = "Initial-password", ["IsActive"] = "true", ["EmailConfirmed"] = "false", }); @@ -233,11 +235,36 @@ public sealed class AdminUsersTests (backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath)); } - private static string AntiforgeryToken(string html) + [Fact] + public async Task StaleEditReloadsTheCurrentAccountAndShowsTheConflict() { - var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; - Assert.NotEmpty(token); - return token; + var backend = new AdminUsersBackend(staleEdit: true); + await using var application = CreateApplication(backend); + using var client = CreateClient(application); + SignIn(application.Services, client, UserRoles.Admin); + var ct = TestContext.Current.CancellationToken; + using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct); + using var form = new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = AntiforgeryToken(await editPage.Content.ReadAsStringAsync(ct)), + ["FirstName"] = "Jan", + ["LastName"] = "Novák", + ["Email"] = "novak@example.test", + ["Role"] = UserRoles.Admin, + ["RowVersion"] = "2", + }); + + using var response = await client.PostAsync(UsersPath + "/7/edit?q=Jan", form, ct); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.StartsWith(UsersPath + "/7/edit?q=Jan", response.Headers.Location?.OriginalString); + Assert.Contains("\"rowVersion\":2", backend.Requests[^1].Body); + + using var fresh = await client.GetAsync(response.Headers.Location, ct); + Assert.Equal(HttpStatusCode.OK, fresh.StatusCode); + var html = WebUtility.HtmlDecode(await fresh.Content.ReadAsStringAsync(ct)); + Assert.Contains("Účet se mezitím změnil.", html); + Assert.Matches("""]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", html); + Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html); } private static WebApplicationFactory CreateApplication(AdminUsersBackend backend) => @@ -252,7 +279,7 @@ public sealed class AdminUsersTests BaseAddress = new Uri("https://localhost"), }); - private sealed class AdminUsersBackend(bool failVerification = false) : HttpMessageHandler + private sealed class AdminUsersBackend(bool failVerification = false, bool staleEdit = false) : HttpMessageHandler { public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = []; @@ -268,6 +295,13 @@ public sealed class AdminUsersTests {"id":7,"email":"novak@example.test","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"verificationEmailSent":false} """, Encoding.UTF8, "application/json"), }; + if (request.Method == HttpMethod.Put && uri.AbsolutePath == "/api/v1/admin/users/7" && staleEdit) + return new HttpResponseMessage(HttpStatusCode.Conflict) + { + Content = new StringContent(""" + {"type":"urn:ntbug:account-version-conflict","title":"Účet se mezitím změnil.","status":409} + """, Encoding.UTF8, "application/problem+json"), + }; if (request.Method != HttpMethod.Get) return new HttpResponseMessage(HttpStatusCode.NoContent); @@ -275,7 +309,7 @@ public sealed class AdminUsersTests return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(""" - {"id":7,"email":"novak@example.test","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true} + {"id":7,"email":"novak@example.test","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"rowVersion":3} """, Encoding.UTF8, "application/json"), }; diff --git a/web/Helpdesk.Web.Tests/AuthAndErrorsTests.cs b/web/Helpdesk.Web.Tests/AuthAndErrorsTests.cs index e9256ec..1b0dd0d 100644 --- a/web/Helpdesk.Web.Tests/AuthAndErrorsTests.cs +++ b/web/Helpdesk.Web.Tests/AuthAndErrorsTests.cs @@ -100,9 +100,9 @@ public class ModelStateExtensionsTests var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.", new Dictionary { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] }); - modelState.AddApiErrors(error, typeof(ResetPasswordViewModel)); + modelState.AddApiErrors(error, typeof(EmailPasswordViewModel)); - Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage); + Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(EmailPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage); Assert.False(modelState.ContainsKey(string.Empty)); } diff --git a/web/Helpdesk.Web.Tests/IssueActionFormTests.cs b/web/Helpdesk.Web.Tests/IssueActionFormTests.cs new file mode 100644 index 0000000..41963ed --- /dev/null +++ b/web/Helpdesk.Web.Tests/IssueActionFormTests.cs @@ -0,0 +1,109 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Helpdesk.Web.Api; +using Helpdesk.Web.Auth; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using static Helpdesk.Web.Tests.WebTestSession; + +namespace Helpdesk.Web.Tests; + +public sealed class IssueActionFormTests +{ + [Theory] + [InlineData("assign", "/assign")] + [InlineData("transition", "/reject")] + [InlineData("edit", "")] + public async Task IssueActionsRequireAnExplicitValidVersionAndAcceptZero(string action, string apiAction) + { + var backend = new IssueBackend(); + await using var application = new WebApplicationFactory().WithWebHostBuilder(builder => + builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient)) + .ConfigurePrimaryHttpMessageHandler(() => backend))); + using var client = application.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri("https://localhost"), + }); + SignIn(application.Services, client, UserRoles.Admin); + var ct = TestContext.Current.CancellationToken; + const string detail = "/issues/42"; + using var page = await client.GetAsync(detail, ct); + Assert.Equal(HttpStatusCode.OK, page.StatusCode); + var fields = action switch + { + "assign" => new Dictionary { ["AssigneeId"] = "7", ["Priority"] = "HIGH" }, + "transition" => new Dictionary { ["Action"] = IssueActions.Reject, ["Text"] = "Duplicitní hlášení." }, + _ => new Dictionary { ["Title"] = "Projektor", ["Description"] = "Bliká.", ["CategoryId"] = "2" }, + }; + fields["__RequestVerificationToken"] = AntiforgeryToken(await page.Content.ReadAsStringAsync(ct)); + var route = $"{detail}/{action}"; + + using (var missing = new FormUrlEncodedContent(fields)) + using (var response = await client.PostAsync(route + "?RowVersion=0", missing, ct)) + { + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal(detail, response.Headers.Location?.OriginalString); + } + + foreach (var invalidVersion in new[] { "", "abc", "-1", "2147483648" }) + { + fields["RowVersion"] = invalidVersion; + using var form = new FormUrlEncodedContent(fields); + using var response = await client.PostAsync(route, form, ct); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal(detail, response.Headers.Location?.OriginalString); + } + + fields["RowVersion"] = "0"; + if (action == "assign") + { + fields["Priority"] = "UNKNOWN"; + using var invalid = new FormUrlEncodedContent(fields); + using var response = await client.PostAsync(route, invalid, ct); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + using var next = await client.GetAsync(detail, ct); + Assert.Contains("Vyberte platnou prioritu.", WebUtility.HtmlDecode(await next.Content.ReadAsStringAsync(ct))); + fields["Priority"] = "HIGH"; + } + + Assert.Empty(backend.Writes); + using var valid = new FormUrlEncodedContent(fields); + using var accepted = await client.PostAsync(route, valid, ct); + Assert.Equal(HttpStatusCode.Redirect, accepted.StatusCode); + var saved = Assert.Single(backend.Writes); + Assert.Equal("/api/v1/issues/42" + apiAction, saved.Path); + Assert.Equal(0, saved.Body.GetProperty("rowVersion").GetInt32()); + if (action == "assign") + Assert.Equal("HIGH", saved.Body.GetProperty("priority").GetString()); + } + + private sealed class IssueBackend : HttpMessageHandler + { + private const string Detail = """ + {"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"status":"RECEIVED","priority":"NORMAL", + "reporterId":1,"createdAt":"2026-10-03T08:00:00Z","rowVersion":0,"allowedActions":["ASSIGN","REJECT","EDIT"],"attachments":[]} + """; + + public List<(string Path, JsonElement Body)> Writes { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var path = request.RequestUri!.AbsolutePath; + var detail = path == "/api/v1/issues/42"; + if (request.Method != HttpMethod.Get) + { + Writes.Add((path, await request.Content!.ReadFromJsonAsync(ct))); + detail = true; + } + + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(detail ? Detail : "[]", Encoding.UTF8, "application/json"), + }; + } + } +} diff --git a/web/Helpdesk.Web.Tests/IssueDetailTests.cs b/web/Helpdesk.Web.Tests/IssueDetailTests.cs index ce0d590..e5129d1 100644 --- a/web/Helpdesk.Web.Tests/IssueDetailTests.cs +++ b/web/Helpdesk.Web.Tests/IssueDetailTests.cs @@ -3,7 +3,10 @@ using System.Net.Http.Headers; using System.Text; using System.Text.Json.Nodes; using Helpdesk.Web.Api; +using Helpdesk.Web.Controllers; using Helpdesk.Web.Models; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; namespace Helpdesk.Web.Tests; @@ -136,6 +139,27 @@ public class IssueActionsApiTests Assert.Equal("image/jpeg", file.ContentType); } + [Theory] + [InlineData("application/pdf", "attachment")] + [InlineData("image/png", "inline")] + public async Task Web_pdf_stahuje_a_png_zobrazuje_v_prohlizeci(string contentType, string expectedDisposition) + { + using var handler = new RecordingHandler("", response => + { + response.Content = new ByteArrayContent([1]); + response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "příloha" }; + }); + var context = new DefaultHttpContext(); + var controller = new IssuesController(Client(handler)) { ControllerContext = new ControllerContext { HttpContext = context } }; + + var result = Assert.IsType(await controller.Attachment(9, CancellationToken.None)); + using var stream = result.FileStream; + var disposition = ContentDispositionHeaderValue.Parse(context.Response.Headers.ContentDisposition.ToString()); + Assert.Equal(expectedDisposition, disposition.DispositionType); + Assert.Equal("příloha", disposition.FileNameStar); + } + [Fact] public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy() { diff --git a/web/Helpdesk.Web.Tests/RegistrationTests.cs b/web/Helpdesk.Web.Tests/RegistrationTests.cs new file mode 100644 index 0000000..a97a46d --- /dev/null +++ b/web/Helpdesk.Web.Tests/RegistrationTests.cs @@ -0,0 +1,140 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using static Helpdesk.Web.Tests.WebTestSession; + +namespace Helpdesk.Web.Tests; + +public sealed class RegistrationTests +{ + [Fact] + public async Task RegistrationOffersToResendAfterTheBackendReportsEmailDeliveryFailure() + { + var backend = new RegistrationBackend(failFirstDelivery: true); + await using var application = new WebApplicationFactory().WithWebHostBuilder(builder => + builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient)) + .ConfigurePrimaryHttpMessageHandler(() => backend))); + using var client = application.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri("https://localhost"), + }); + var ct = TestContext.Current.CancellationToken; + using var registration = await client.GetAsync("/register", ct); + var fields = new Dictionary + { + ["__RequestVerificationToken"] = AntiforgeryToken(await registration.Content.ReadAsStringAsync(ct)), + ["Email"] = "jan@student.example.test", + ["FirstName"] = "Jan", + ["LastName"] = "Novák", + }; + using var initial = new FormUrlEncodedContent(fields); + using var failed = await client.PostAsync("/register", initial, ct); + Assert.Equal(HttpStatusCode.OK, failed.StatusCode); + var retryPage = WebUtility.HtmlDecode(await failed.Content.ReadAsStringAsync(ct)); + Assert.Contains("Účet je uložený.", retryPage); + Assert.Contains("Poslat ověřovací e-mail znovu", retryPage); + Assert.Contains("value=\"jan@student.example.test\"", retryPage); + + fields["__RequestVerificationToken"] = AntiforgeryToken(retryPage); + using var retry = new FormUrlEncodedContent(fields); + using var sent = await client.PostAsync("/register", retry, ct); + Assert.Equal(HttpStatusCode.OK, sent.StatusCode); + Assert.Contains("Ověřte svůj e-mail", WebUtility.HtmlDecode(await sent.Content.ReadAsStringAsync(ct))); + Assert.Equal(2, backend.Requests.Count); + Assert.Equal(backend.Requests[0].Body.GetRawText(), backend.Requests[1].Body.GetRawText()); + } + + [Fact] + public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword() + { + var backend = new RegistrationBackend(); + await using var application = new WebApplicationFactory().WithWebHostBuilder(builder => + builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient)) + .ConfigurePrimaryHttpMessageHandler(() => backend))); + using var client = application.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri("https://localhost"), + }); + var ct = TestContext.Current.CancellationToken; + + using var registration = await client.GetAsync("/register", ct); + var registerHtml = await registration.Content.ReadAsStringAsync(ct); + Assert.DoesNotContain("type=\"password\"", registerHtml); + using var registerForm = new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = AntiforgeryToken(registerHtml), + ["Email"] = "jan@student.example.test", + ["FirstName"] = "Jan", + ["LastName"] = "Novák", + }); + using var registered = await client.PostAsync("/register", registerForm, ct); + Assert.Equal(HttpStatusCode.OK, registered.StatusCode); + var start = Assert.Single(backend.Requests); + Assert.Equal("/api/v1/auth/register", start.Path); + Assert.False(start.Body.TryGetProperty("password", out _)); + + using var link = await client.GetAsync("/confirm-email?token=email-token", ct); + var confirmHtml = await link.Content.ReadAsStringAsync(ct); + Assert.Contains("name=\"NewPassword\"", confirmHtml); + Assert.Contains("name=\"ConfirmPassword\"", confirmHtml); + Assert.Single(backend.Requests); + var form = new Dictionary + { + ["__RequestVerificationToken"] = AntiforgeryToken(confirmHtml), + ["Token"] = "email-token", + ["NewPassword"] = "Mailbox-owner-password", + ["ConfirmPassword"] = "Different-password", + }; + using var invalidForm = new FormUrlEncodedContent(form); + using var invalid = await client.PostAsync("/confirm-email", invalidForm, ct); + Assert.Equal(HttpStatusCode.OK, invalid.StatusCode); + Assert.Contains("Hesla se neshodují.", WebUtility.HtmlDecode(await invalid.Content.ReadAsStringAsync(ct))); + Assert.Single(backend.Requests); + + form["ConfirmPassword"] = form["NewPassword"]; + using var confirmForm = new FormUrlEncodedContent(form); + using var confirmed = await client.PostAsync("/confirm-email", confirmForm, ct); + Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode); + Assert.Equal("/login", confirmed.Headers.Location?.OriginalString); + var confirmation = backend.Requests[1]; + Assert.Equal("/api/v1/auth/confirm-email", confirmation.Path); + Assert.Equal("email-token", confirmation.Body.GetProperty("token").GetString()); + Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString()); + } + + private sealed class RegistrationBackend(bool failFirstDelivery = false) : HttpMessageHandler + { + public List<(string Path, JsonElement Body)> Requests { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Assert.Equal(HttpMethod.Post, request.Method); + var path = request.RequestUri!.AbsolutePath; + using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(ct)); + Requests.Add((path, json.RootElement.Clone())); + if (path == "/api/v1/auth/confirm-email") + return new HttpResponseMessage(HttpStatusCode.NoContent); + + Assert.Equal("/api/v1/auth/register", path); + if (failFirstDelivery && Requests.Count == 1) + return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) + { + Content = new StringContent(""" + {"type":"urn:ntbug:email-delivery-failed","title":"E-mail se nepodařilo odeslat.","status":503} + """, Encoding.UTF8, "application/problem+json"), + }; + return new HttpResponseMessage(HttpStatusCode.Created) + { + Content = new StringContent(""" + {"id":7,"email":"jan@student.example.test","firstName":"Jan","lastName":"Novák","role":"STUDENT","emailNotificationsEnabled":true} + """, Encoding.UTF8, "application/json"), + }; + } + } +} diff --git a/web/Helpdesk.Web.Tests/WebTestSession.cs b/web/Helpdesk.Web.Tests/WebTestSession.cs index 1c844c7..c4a38d0 100644 --- a/web/Helpdesk.Web.Tests/WebTestSession.cs +++ b/web/Helpdesk.Web.Tests/WebTestSession.cs @@ -1,3 +1,4 @@ +using System.Text.RegularExpressions; using Helpdesk.Web.Api; using Helpdesk.Web.Auth; using Microsoft.AspNetCore.Authentication; @@ -9,6 +10,13 @@ namespace Helpdesk.Web.Tests; internal static class WebTestSession { + public static string AntiforgeryToken(string html) + { + var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; + Assert.NotEmpty(token); + return token; + } + public static void SignIn(IServiceProvider services, HttpClient client, string role) { var scheme = CookieAuthenticationDefaults.AuthenticationScheme; diff --git a/web/Helpdesk.Web/Api/ApiException.cs b/web/Helpdesk.Web/Api/ApiException.cs index 985810f..10f3c0e 100644 --- a/web/Helpdesk.Web/Api/ApiException.cs +++ b/web/Helpdesk.Web/Api/ApiException.cs @@ -8,11 +8,12 @@ namespace Helpdesk.Web.Api; /// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek /// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase). /// -public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary errors) +public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary errors, string? problemType = null) : Exception(title ?? $"API vrátilo stav {(int)statusCode}.") { public HttpStatusCode StatusCode { get; } = statusCode; public string? Title { get; } = title; + public string? ProblemType { get; } = problemType; public IReadOnlyDictionary Errors { get; } = errors; /// Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429). @@ -33,6 +34,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead public static async Task FromResponseAsync(HttpResponseMessage response, CancellationToken ct) { string? title = null; + string? type = null; Dictionary errors = new(StringComparer.OrdinalIgnoreCase); if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase)) @@ -41,6 +43,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead { var problem = await response.Content.ReadFromJsonAsync(ct); title = problem?.Title; + type = problem?.Type; if (problem?.Errors is { } fieldErrors) { foreach (var (field, messages) in fieldErrors) @@ -53,10 +56,10 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead } } - return new ApiException(response.StatusCode, title, errors); + return new ApiException(response.StatusCode, title, errors, type); } - private sealed record ProblemBody(string? Title, Dictionary? Errors); + private sealed record ProblemBody(string? Title, Dictionary? Errors, string? Type); } internal static class ApiResponse diff --git a/web/Helpdesk.Web/Api/ApiModels.cs b/web/Helpdesk.Web/Api/ApiModels.cs index d4f965f..4370b36 100644 --- a/web/Helpdesk.Web/Api/ApiModels.cs +++ b/web/Helpdesk.Web/Api/ApiModels.cs @@ -34,11 +34,11 @@ public sealed record TokenSet( public sealed record LoginRequest(string Email, string Password); -public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName); +public sealed record RegisterRequest(string Email, string FirstName, string LastName); public sealed record RefreshTokenRequest(string RefreshToken); -public sealed record EmailTokenRequest(string Token); +public sealed record ConfirmEmailRequest(string Token, string NewPassword); public sealed record ForgotPasswordRequest(string Email); @@ -53,10 +53,11 @@ public sealed record AdminUserDto( } 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 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); /// Stránkovaný seznam z API: { items, totalCount, page, pageSize }. public sealed record PagedResult(IReadOnlyList Items, int TotalCount, int Page, int PageSize) diff --git a/web/Helpdesk.Web/Api/AuthApiClient.cs b/web/Helpdesk.Web/Api/AuthApiClient.cs index 4351947..36f050f 100644 --- a/web/Helpdesk.Web/Api/AuthApiClient.cs +++ b/web/Helpdesk.Web/Api/AuthApiClient.cs @@ -22,9 +22,9 @@ public sealed class AuthApiClient(HttpClient http) return await ApiResponse.ReadAsync(response, ct); } - public async Task ConfirmEmailAsync(string token, CancellationToken ct) + public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct) { - using var response = await http.PostAsJsonAsync("auth/confirm-email", new EmailTokenRequest(token), ct); + using var response = await http.PostAsJsonAsync("auth/confirm-email", request, ct); await ApiResponse.EnsureSuccessAsync(response, ct); } diff --git a/web/Helpdesk.Web/Controllers/AccountController.cs b/web/Helpdesk.Web/Controllers/AccountController.cs index c56a35e..3fbba6a 100644 --- a/web/Helpdesk.Web/Controllers/AccountController.cs +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -44,7 +44,6 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests) { - // 401 špatné heslo / zamčený účet, 403 neověřený e-mail nebo deaktivovaný účet – API vrací český text. ModelState.AddApiErrors(ex, typeof(LoginViewModel)); model.Password = ""; return View(model); @@ -66,39 +65,48 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a try { var user = await authApi.RegisterAsync( - new RegisterRequest(model.Email.Trim(), model.Password, model.FirstName.Trim(), model.LastName.Trim()), ct); + new RegisterRequest(model.Email.Trim(), model.FirstName.Trim(), model.LastName.Trim()), ct); return View("RegisterDone", user.Email); } - catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.TooManyRequests) + catch (ApiException ex) when (ex is { StatusCode: HttpStatusCode.ServiceUnavailable, ProblemType: "urn:ntbug:email-delivery-failed" }) + { + ViewData["VerificationEmailFailed"] = true; + ModelState.AddModelError(string.Empty, "Účet je uložený. Ověřovací e-mail se nepodařilo odeslat, zkuste ho prosím poslat znovu."); + return View(model); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict + or HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable) { - // 400 cizí doména nebo validace, 409 účet už existuje. ModelState.AddApiErrors(ex, typeof(RegisterViewModel)); - model.Password = model.ConfirmPassword = ""; return View(model); } } - /// Odkaz z registračního e-mailu. Token se spotřebuje až tlačítkem, ne samotným otevřením odkazu. + /// Odkaz z ověřovacího e-mailu. Token se spotřebuje při uložení hesla. [AllowAnonymous] [HttpGet("confirm-email")] - public IActionResult ConfirmEmail(string? token) => View(new EmailTokenViewModel { Token = token ?? "" }); + public IActionResult ConfirmEmail(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" }); [AllowAnonymous] [HttpPost("confirm-email")] - public async Task ConfirmEmail(EmailTokenViewModel model, CancellationToken ct) + public async Task ConfirmEmail(EmailPasswordViewModel model, CancellationToken ct) { if (!ModelState.IsValid) + { + model.NewPassword = model.ConfirmPassword = ""; return View(model); + } try { - await authApi.ConfirmEmailAsync(model.Token, ct); - TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit."); + await authApi.ConfirmEmailAsync(new ConfirmEmailRequest(model.Token, model.NewPassword), ct); + TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit nastaveným heslem."); return RedirectToAction(nameof(Login)); } catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests) { - ModelState.AddModelError(string.Empty, ex.UserMessage); + ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel)); + model.NewPassword = model.ConfirmPassword = ""; return View(model); } } @@ -128,11 +136,11 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a [AllowAnonymous] [HttpGet("reset-password")] - public IActionResult ResetPassword(string? token) => View(new ResetPasswordViewModel { Token = token ?? "" }); + public IActionResult ResetPassword(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" }); [AllowAnonymous] [HttpPost("reset-password")] - public async Task ResetPassword(ResetPasswordViewModel model, CancellationToken ct) + public async Task ResetPassword(EmailPasswordViewModel model, CancellationToken ct) { if (!ModelState.IsValid) { @@ -146,7 +154,7 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a } catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests) { - ModelState.AddApiErrors(ex, typeof(ResetPasswordViewModel)); + ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel)); model.NewPassword = model.ConfirmPassword = ""; return View(model); } diff --git a/web/Helpdesk.Web/Controllers/AdminUsersController.cs b/web/Helpdesk.Web/Controllers/AdminUsersController.cs index d00b392..43a3b3c 100644 --- a/web/Helpdesk.Web/Controllers/AdminUsersController.cs +++ b/web/Helpdesk.Web/Controllers/AdminUsersController.cs @@ -45,6 +45,7 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller { Id = user.Id, Query = query, + RowVersion = user.RowVersion, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, @@ -162,10 +163,16 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller if (id is not null && id == CurrentUserId) return RedirectToAction("Index", "Profile"); + if (id is int userId && model.RowVersion is null or < 0) + { + TempData.SetError("Formulář nemá platnou verzi účtu. Změny zadejte znovu."); + return BackToEdit(userId, query); + } + model.Id = id; model.Query = query; - if (id is null && string.IsNullOrWhiteSpace(model.Password)) - ModelState.AddModelError(nameof(model.Password), "Zadejte počáteční heslo."); + if (id is null && model.EmailConfirmed && string.IsNullOrWhiteSpace(model.Password)) + ModelState.AddModelError(nameof(model.Password), "Při ručním ověření e-mailu zadejte počáteční heslo."); if (ModelState.IsValid) { try @@ -180,6 +187,12 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller } return BackToList(query); } + catch (ApiException ex) when (id is int editedUserId && ex is + { StatusCode: HttpStatusCode.Conflict, ProblemType: "urn:ntbug:account-version-conflict" }) + { + TempData.SetError(ex.UserMessage); + return BackToEdit(editedUserId, query); + } catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict) { ModelState.AddApiErrors(ex, typeof(AdminUserForm)); diff --git a/web/Helpdesk.Web/Controllers/IssuesController.cs b/web/Helpdesk.Web/Controllers/IssuesController.cs index ef64622..5036c90 100644 --- a/web/Helpdesk.Web/Controllers/IssuesController.cs +++ b/web/Helpdesk.Web/Controllers/IssuesController.cs @@ -85,11 +85,13 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller /// Změna stavu: zahájit, předat k ověření, potvrdit, znovu otevřít, zamítnout (T4 – T9). [HttpPost("{id:int}/transition")] - public async Task Transition(int id, IssueActionForm form, CancellationToken ct) + public async Task Transition(int id, [FromForm] IssueActionForm form, CancellationToken ct) { var action = form.Action ?? ""; if (IssueActions.TransitionPath(action) is null) return BadRequest(); + if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0) + return BackToDetail(id, error: InvalidActionFormMessage); var text = string.IsNullOrWhiteSpace(form.Text) || !IssueActions.AcceptsText(action) ? null : form.Text.Trim(); if (IssueActions.RequiresReason(action) && text is null) @@ -97,7 +99,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller if (text?.Length > IssueActionForm.MaxTextLength) return BackToDetail(id, error: $"Text může mít nejvýše {IssueActionForm.MaxTextLength} znaků."); - return await RunAsync(id, () => api.TransitionIssueAsync(id, action, form.RowVersion, text, ct), action switch + return await RunAsync(id, () => api.TransitionIssueAsync(id, action, rowVersion, text, ct), action switch { IssueActions.StartWork => "Řešení závady je zahájené.", IssueActions.SubmitForVerification => "Závada je předaná k ověření. Hlásič potvrdí, jestli je vyřešená.", @@ -109,13 +111,16 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller /// Přiřazení nebo přeřazení řešiteli (T2, T3) – jen vedení. [HttpPost("{id:int}/assign")] - public async Task Assign(int id, IssueActionForm form, CancellationToken ct) + public async Task Assign(int id, [FromForm] IssueActionForm form, CancellationToken ct) { + if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0) + return BackToDetail(id, error: InvalidActionFormMessage); if (form.AssigneeId is not { } assigneeId) return BackToDetail(id, error: "Vyberte řešitele."); - var priority = IssuePriorities.All.Contains(form.Priority) ? form.Priority : null; + if (form.Priority is not null && !IssuePriorities.All.Contains(form.Priority)) + return BackToDetail(id, error: "Vyberte platnou prioritu."); - return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, priority, form.RowVersion), ct), + return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, form.Priority, rowVersion), ct), "Závada je přiřazená řešiteli."); } @@ -174,21 +179,23 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller } [HttpPost("{id:int}/edit")] - public async Task Edit(int id, EditIssueViewModel model, CancellationToken ct) + public async Task Edit(int id, [FromForm] EditIssueViewModel model, CancellationToken ct) { model.Id = id; + if (model.RowVersion is not int rowVersion || rowVersion < 0) + return BackToDetail(id, error: InvalidActionFormMessage); if (!ModelState.IsValid) return View(await WithCatalogsAsync(model, ct)); try { await api.EditIssueAsync(id, new EditIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value, - model.BuildingId, model.LocationDetail?.Trim(), model.RowVersion), ct); + model.BuildingId, model.LocationDetail?.Trim(), rowVersion), ct); return BackToDetail(id, success: "Změny hlášení jsou uložené."); } catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict) { - return BackToDetail(id, error: ConflictMessage); + return BackToDetail(id, error: ConflictError(ex)); } catch (ApiException ex) when (IsUserError(ex)) { @@ -197,9 +204,15 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller } } + private const string InvalidActionFormMessage = + "Formulář obsahuje chybějící nebo neplatné údaje. Zkontrolujte aktuální detail závady a akci zopakujte."; + private const string ConflictMessage = "Závadu mezitím někdo změnil. Níže je její aktuální stav – zkontrolujte ho a akci případně zopakujte."; + private static string ConflictError(ApiException ex) => + ex.ProblemType == "urn:ntbug:issue-version-conflict" ? ConflictMessage : ex.UserMessage; + /// /// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může /// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje . @@ -213,8 +226,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller } catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict) { - // 409: jiná rowVersion (někdo závadu mezitím změnil), nebo akce v aktuálním stavu už nejde. - return BackToDetail(id, error: ConflictMessage); + return BackToDetail(id, error: ConflictError(ex)); } catch (ApiException ex) when (IsUserError(ex)) { diff --git a/web/Helpdesk.Web/Models/AccountModels.cs b/web/Helpdesk.Web/Models/AccountModels.cs index 3d36ff1..e20aae7 100644 --- a/web/Helpdesk.Web/Models/AccountModels.cs +++ b/web/Helpdesk.Web/Models/AccountModels.cs @@ -43,25 +43,6 @@ public sealed class RegisterViewModel [StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")] [Display(Name = "Příjmení")] public string LastName { get; set; } = ""; - - [Required(ErrorMessage = "Zadejte heslo.")] - [StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)] - [DataType(DataType.Password)] - [Display(Name = "Heslo")] - public string Password { get; set; } = ""; - - [Required(ErrorMessage = "Zadejte heslo znovu.")] - [Compare(nameof(Password), ErrorMessage = "Hesla se neshodují.")] - [DataType(DataType.Password)] - [Display(Name = "Heslo znovu")] - public string ConfirmPassword { get; set; } = ""; -} - -/// Stránka z odkazu v e-mailu – token se odešle až tlačítkem. -public sealed class EmailTokenViewModel -{ - [Required] - public string Token { get; set; } = ""; } public sealed class ForgotPasswordViewModel @@ -72,7 +53,7 @@ public sealed class ForgotPasswordViewModel public string Email { get; set; } = ""; } -public sealed class ResetPasswordViewModel +public sealed class EmailPasswordViewModel { [Required] public string Token { get; set; } = ""; diff --git a/web/Helpdesk.Web/Models/AdminUsersViewModel.cs b/web/Helpdesk.Web/Models/AdminUsersViewModel.cs index 024b229..4e0a021 100644 --- a/web/Helpdesk.Web/Models/AdminUsersViewModel.cs +++ b/web/Helpdesk.Web/Models/AdminUsersViewModel.cs @@ -17,6 +17,8 @@ public sealed class AdminUserForm [BindNever] public AdminUsersQuery Query { get; set; } = new(); + public int? RowVersion { get; set; } + [Display(Name = "Jméno"), Required(ErrorMessage = "Zadejte jméno."), StringLength(100)] public string FirstName { get; set; } = ""; @@ -46,5 +48,5 @@ public sealed class AdminUserForm public bool EmailNotificationsEnabled { get; set; } = true; public SaveAdminUserRequest ToRequest() => new(Email.Trim(), FirstName.Trim(), LastName.Trim(), Phone, - Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password); + Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password, RowVersion); } diff --git a/web/Helpdesk.Web/Models/IssueDetailViewModel.cs b/web/Helpdesk.Web/Models/IssueDetailViewModel.cs index 3790ea3..6a4c5f6 100644 --- a/web/Helpdesk.Web/Models/IssueDetailViewModel.cs +++ b/web/Helpdesk.Web/Models/IssueDetailViewModel.cs @@ -53,7 +53,7 @@ public sealed class IssueDetailViewModel }; /// Fotky a PDF otevře prohlížeč rovnou, ostatní (DOCX, HEIC) se stáhnou. - public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png" or "application/pdf"; + public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png"; } public static class IssueEventTypes @@ -97,7 +97,7 @@ public sealed record TimelineEntry(IssueEventDto Event, string Text, string? Not /// Formuláře akcí na detailu závady. Každý POST použije jen svá pole. public sealed class IssueActionForm { - public int RowVersion { get; set; } + public int? RowVersion { get; set; } public string? Action { get; set; } /// Důvod (zamítnutí, znovuotevření) nebo poznámka (předání k ověření). diff --git a/web/Helpdesk.Web/Models/NewIssueViewModel.cs b/web/Helpdesk.Web/Models/NewIssueViewModel.cs index 2a1dd32..41d468f 100644 --- a/web/Helpdesk.Web/Models/NewIssueViewModel.cs +++ b/web/Helpdesk.Web/Models/NewIssueViewModel.cs @@ -85,7 +85,7 @@ public sealed class EditIssueViewModel : IssueFormViewModel public int Id { get; set; } /// Verze, kterou uživatel upravuje; když se závada mezitím změní, API vrátí 409. - public int RowVersion { get; set; } + public int? RowVersion { get; set; } public static EditIssueViewModel From(IssueDetail issue) => new() { diff --git a/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml b/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml index 9c9ce25..04c68d1 100644 --- a/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml +++ b/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml @@ -1,27 +1,28 @@ -@model EmailTokenViewModel +@model EmailPasswordViewModel @{ ViewData["Title"] = "Ověření e-mailu"; - var failed = !ViewData.ModelState.IsValid || string.IsNullOrEmpty(Model.Token); }

Ověření e-mailu

- @if (failed) + @if (string.IsNullOrEmpty(Model.Token)) { - -

Odkaz je neplatný, už byl použit, nebo vypršel. Pokud jste e-mail už ověřili, stačí se přihlásit.

+

Odkaz je neúplný. Otevřete ho prosím znovu z e-mailu.

} else { -

Dokončete registraci potvrzením svého e-mailu.

-
+

Nastavením hesla ověříte svůj e-mail.

+ + - + + }
diff --git a/web/Helpdesk.Web/Views/Account/Register.cshtml b/web/Helpdesk.Web/Views/Account/Register.cshtml index 57178bb..f5bc77a 100644 --- a/web/Helpdesk.Web/Views/Account/Register.cshtml +++ b/web/Helpdesk.Web/Views/Account/Register.cshtml @@ -1,6 +1,7 @@ @model RegisterViewModel @{ ViewData["Title"] = "Registrace"; + var resend = ViewData["VerificationEmailFailed"] is true; }
@@ -27,18 +28,7 @@ -
- - -
8 až 64 znaků.
- -
-
- - - -
- + diff --git a/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml b/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml index 26f20c4..9de782d 100644 --- a/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml +++ b/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml @@ -7,7 +7,7 @@

Ověřte svůj e-mail

Na adresu @Model jsme poslali odkaz pro ověření e-mailu. Platí 24 hodin.

-

Po ověření se budete moct přihlásit. Pokud e-mail nevidíte, podívejte se i do nevyžádané pošty.

+

Po otevření odkazu si nastavíte heslo k účtu. Pokud e-mail nevidíte, podívejte se i do nevyžádané pošty.