From 722d3188982a423625fa92cb1cd7e679679da617 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Sat, 5 Dec 2026 02:42:22 +0100 Subject: [PATCH] backend + web: Improve validation and email retry handling --- .../Controllers/IssuesController.cs | 10 +-- .../Helpdesk.Application/Auth/AuthService.cs | 2 +- .../src/Helpdesk.Application/Common/Errors.cs | 12 +++- .../Issues/IssueService.cs | 66 +++++++++++++------ .../Files/FileAttachmentStore.cs | 12 ++-- .../AttachmentTests.cs | 4 +- .../EmailConfirmationTests.cs | 26 ++++++++ .../IssueWorkflowTests.cs | 37 ++++++++++- docs/navrh-aplikace.md | 2 +- web/Helpdesk.Web.Tests/RegistrationTests.cs | 47 ++++++++++++- .../Controllers/AccountController.cs | 10 ++- .../Controllers/IssuesController.cs | 8 ++- .../Views/Account/Register.cshtml | 3 +- 13 files changed, 195 insertions(+), 44 deletions(-) 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.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index 436f759..c2a5037 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -29,7 +29,7 @@ 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); diff --git a/backend/src/Helpdesk.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index 551b8bd..171ca17 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -1,3 +1,6 @@ +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. @@ -12,7 +15,7 @@ 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; } @@ -38,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.Infrastructure/Files/FileAttachmentStore.cs b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs index c22479f..1419c74 100644 --- a/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs +++ b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs @@ -13,11 +13,11 @@ internal sealed class FileAttachmentStore(ILogger logger) : 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,7 +27,7 @@ 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(UploadDirectory); @@ -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); } 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/EmailConfirmationTests.cs b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs index bd697c9..28c0fd4 100644 --- a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs @@ -19,6 +19,32 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu 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() { 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/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 60365d9..9f1c25d 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -656,7 +656,7 @@ 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, jméno, příjmení) a odeslání ověřovacího odkazu | +| 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) | diff --git a/web/Helpdesk.Web.Tests/RegistrationTests.cs b/web/Helpdesk.Web.Tests/RegistrationTests.cs index 3aea38f..a97a46d 100644 --- a/web/Helpdesk.Web.Tests/RegistrationTests.cs +++ b/web/Helpdesk.Web.Tests/RegistrationTests.cs @@ -11,6 +11,44 @@ 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() { @@ -70,7 +108,7 @@ public sealed class RegistrationTests Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString()); } - private sealed class RegistrationBackend : HttpMessageHandler + private sealed class RegistrationBackend(bool failFirstDelivery = false) : HttpMessageHandler { public List<(string Path, JsonElement Body)> Requests { get; } = []; @@ -84,6 +122,13 @@ public sealed class RegistrationTests 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(""" diff --git a/web/Helpdesk.Web/Controllers/AccountController.cs b/web/Helpdesk.Web/Controllers/AccountController.cs index 087a351..3fbba6a 100644 --- a/web/Helpdesk.Web/Controllers/AccountController.cs +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -68,9 +68,15 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a 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)); return View(model); } diff --git a/web/Helpdesk.Web/Controllers/IssuesController.cs b/web/Helpdesk.Web/Controllers/IssuesController.cs index 14455d2..5036c90 100644 --- a/web/Helpdesk.Web/Controllers/IssuesController.cs +++ b/web/Helpdesk.Web/Controllers/IssuesController.cs @@ -195,7 +195,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller } 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)) { @@ -210,6 +210,9 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller 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 . @@ -223,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/Views/Account/Register.cshtml b/web/Helpdesk.Web/Views/Account/Register.cshtml index db41f84..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,7 +28,7 @@ - +