backend + web: Improve validation and email retry handling

This commit is contained in:
GonnaHetzMe committed 2026-12-05 02:42:22 +01:00
1 parent e9782a1413
commit 722d318898
13 files changed
+195 -44

No files matched your search

@@ -41,6 +41,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)] [RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)] [RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)] [ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)] [ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)] [ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)] [ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
@@ -55,7 +56,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
var form = await ReadFormAsync(ct); var form = await ReadFormAsync(ct);
request = new CreateIssueRequest( request = new CreateIssueRequest(
form["title"].ToString(), form["description"].ToString(), 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()); ReadId(form, "buildingId"), form["locationDetail"].ToString());
uploads = ReadUploads(form.Files); uploads = ReadUploads(form.Files);
} }
@@ -87,6 +88,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
} }
[HttpPut("{id:int}")] [HttpPut("{id:int}")]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) => public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
issues.EditAsync(id, request, ct); issues.EditAsync(id, request, ct);
@@ -160,16 +162,16 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
if (string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
return null; return null;
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id)) 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; return id;
} }
private static AttachmentUpload[] ReadUploads(IFormFileCollection files) private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
{ {
if (files.Count > AttachmentLimits.MaxFiles) 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")) 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(); return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
} }
@@ -29,7 +29,7 @@ public sealed class AuthService(
await registerValidator.ValidateAndThrowAsync(request, ct); await registerValidator.ValidateAndThrowAsync(request, ct);
var role = _registration.ResolveRole(request.Email) 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 normalized = User.NormalizeEmail(request.Email);
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct); var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
@@ -1,3 +1,6 @@
using FluentValidation;
using FluentValidation.Results;
namespace Helpdesk.Application.Common; namespace Helpdesk.Application.Common;
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary> /// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
@@ -12,7 +15,7 @@ public sealed class NotFoundException(string message) : AppException(message)
public override int StatusCode => 404; 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 override int StatusCode => 409;
} }
@@ -38,8 +41,13 @@ public sealed class BadRequestException(string message) : AppException(message)
public override int StatusCode => 400; 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) 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 string Reason { get; } = reason;
public bool Retryable { get; } = retryable; public bool Retryable { get; } = retryable;
@@ -1,4 +1,6 @@
using System.Text; using System.Text;
using FluentValidation;
using FluentValidation.Results;
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common; using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications; using Helpdesk.Application.Notifications;
@@ -44,11 +46,17 @@ public sealed partial class IssueService(
CheckVersion(issue, request.RowVersion); CheckVersion(issue, request.RowVersion);
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct); var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
if (assignee is null || !Issue.CanBeAssigned(assignee.Role)) 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) if (issue.AssigneeId == assignee.Id)
throw new ConflictException("Závada je již přiřazena tomuto řešiteli."); throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority); IssuePriority? priority = null;
if (request.Priority is { } code)
{
if (!EnumCode.TryParse<IssuePriority>(code, out var selected))
throw new FieldValidationException(nameof(request.Priority), "Vyberte platnou prioritu.");
priority = selected;
}
var from = issue.Status; var from = issue.Status;
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority); issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName); 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); var (issue, actor) = await LoadActionAsync(id, action, ct);
CheckVersion(issue, version); CheckVersion(issue, version);
note = action is IssueAction.Reopen or IssueAction.Reject note = action is IssueAction.Reopen or IssueAction.Reject
? RequiredText(note, "Důvod", MaxTextBytes) ? RequiredText(note, nameof(IssueReasonRequest.Reason), "Důvod")
: OptionalText(note, "Poznámka", MaxTextBytes); : OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka");
var from = issue.Status; var from = issue.Status;
issue.Transition(action, actor.Id, actor.Role, note); issue.Transition(action, actor.Id, actor.Role, note);
@@ -87,7 +95,7 @@ public sealed partial class IssueService(
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct) public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
{ {
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, 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); issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text); var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId]; 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 (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
var uploads = await readUploads(ct); var uploads = await readUploads(ct);
if (uploads.Length == 0) 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); issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct); var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
@@ -113,7 +121,7 @@ public sealed partial class IssueService(
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct) Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
{ {
if (uploads.Count > AttachmentLimits.MaxFiles) 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<Attachment>(uploads.Count); var attachments = new List<Attachment>(uploads.Count);
var saving = false; var saving = false;
@@ -172,18 +180,31 @@ public sealed partial class IssueService(
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct) private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
{ {
var title = RequiredText(request.Title, "Název", MaxTextBytes); var errors = new List<ValidationFailure>();
RequiredText(request.Description, "Popis", MaxTextBytes); var title = request.Title?.Trim();
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255) if (string.IsNullOrEmpty(title))
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků."); 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 && if (original?.CategoryId != request.CategoryId &&
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct)) !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 && if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct)) !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) private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
@@ -201,30 +222,33 @@ public sealed partial class IssueService(
} }
catch (DbUpdateConcurrencyException) 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) private static void CheckVersion(Issue issue, int? supplied)
{ {
if (supplied is null or < 0) 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) 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 const int MaxTextBytes = 65_535;
private static string RequiredText(string? input, string name, int maxBytes) => private static string RequiredText(string? input, string field, string label) =>
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná."); 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(); var text = input?.Trim();
if (string.IsNullOrEmpty(text)) if (string.IsNullOrEmpty(text))
return null; return null;
if (Encoding.UTF8.GetByteCount(text) > maxBytes) if (Encoding.UTF8.GetByteCount(text) > MaxTextBytes)
throw new BadRequestException($"{name}: hodnota je příliš dlouhá."); throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá.");
return text; return text;
} }
@@ -13,11 +13,11 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct) public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
{ {
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes) 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(); var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
if (name.Length is 0 or > 255 || name.Any(char.IsControl)) 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 extension = Path.GetExtension(name).ToLowerInvariant();
var contentType = extension switch var contentType = extension switch
@@ -27,7 +27,7 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
".heic" => "image/heic", ".heic" => "image/heic",
".pdf" => "application/pdf", ".pdf" => "application/pdf",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".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); Directory.CreateDirectory(UploadDirectory);
@@ -49,16 +49,16 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
{ {
written += read; written += read;
if (written > upload.SizeBytes) 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); await output.WriteAsync(buffer.AsMemory(0, read), ct);
} }
if (written != upload.SizeBytes) 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; output.Position = 0;
if (!await HasExpectedFormatAsync(output, extension, ct)) 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); return new StoredAttachment(name, key, contentType, written);
} }
@@ -5,6 +5,7 @@ using System.Net.Http.Json;
using Helpdesk.Application.Catalogs; using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues; using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture; using static Helpdesk.IntegrationTests.BackendFixture;
@@ -49,7 +50,8 @@ public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<Back
using var mixed = new MultipartFormDataContent(); using var mixed = new MultipartFormDataContent();
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray()); AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray()); AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest); var validation = await ReadAsync<ValidationProblemDetails>(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
Assert.Equal("files", Assert.Single(validation.Errors.Keys));
using var wrongField = new MultipartFormDataContent(); using var wrongField = new MultipartFormDataContent();
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png"); wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
@@ -19,6 +19,32 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu
private const string Confirm = "/api/v1/auth/confirm-email"; private const string Confirm = "/api/v1/auth/confirm-email";
private const string Login = "/api/v1/auth/login"; private const string Login = "/api/v1/auth/login";
[Fact]
public async Task FailedRegistrationEmailCanBeRetriedForTheSameAccount()
{
using var anonymous = fixture.CreateClient();
const string address = "[email protected]";
var request = new RegisterRequest(address, "Jan", "Novák");
fixture.FailNextEmail(address, "SMTP_UNAVAILABLE", retryable: true);
var failure = await ReadAsync<ProblemDetails>(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<HelpdeskDbContext>();
var pending = await db.Users.AsNoTracking().SingleAsync(user => user.Email == address, Cancellation);
Assert.False(pending.EmailConfirmed);
Assert.Empty(pending.PasswordHash);
var retried = await ReadAsync<UserDto>(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] [Fact]
public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt() public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt()
{ {
@@ -5,12 +5,46 @@ using Helpdesk.Application.Common;
using Helpdesk.Application.Issues; using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications; using Helpdesk.Application.Notifications;
using Helpdesk.Application.Statistics; using Helpdesk.Application.Statistics;
using Microsoft.AspNetCore.Mvc;
using static Helpdesk.IntegrationTests.BackendFixture; using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests; namespace Helpdesk.IntegrationTests;
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture> public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{ {
[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<ValidationProblemDetails>(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<ValidationProblemDetails>(admin.PostAsync(issues, form, Cancellation), HttpStatusCode.BadRequest);
Assert.Equal("categoryId", Assert.Single(uploadError.Errors.Keys));
var categories = await ReadAsync<CategoryDto[]>(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<ValidationProblemDetails>(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<ValidationProblemDetails>(admin.PostAsJsonAsync(path + "/assign", assign, Cancellation),
HttpStatusCode.BadRequest);
Assert.Equal("priority", Assert.Single(priorityError.Errors.Keys));
var saved = await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation));
Assert.Equal((issue.RowVersion, issue.CategoryId, issue.AssigneeId), (saved.RowVersion, saved.CategoryId, saved.AssigneeId));
}
[Fact] [Fact]
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt() public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
{ {
@@ -52,8 +86,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation)); var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id); Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id);
Assert.Contains(assignable, user => user.Id == administrator.User.Id); Assert.Contains(assignable, user => user.Id == administrator.User.Id);
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start", var conflict = await ReadAsync<ProblemDetails>(firstSolver.PostAsJsonAsync(path + "/start",
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict); new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
Assert.Equal("urn:ntbug:issue-version-conflict", conflict.Type);
var reporterNotifications = await InboxAsync(reporter, issue.Id); var reporterNotifications = await InboxAsync(reporter, issue.Id);
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type); Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
+1 -1
View File
@@ -656,7 +656,7 @@ Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/
### Autentizace a účet ### Autentizace a účet
| Metoda | Endpoint | Role | Popis | | 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/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/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/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) |
+46 -1
View File
@@ -11,6 +11,44 @@ namespace Helpdesk.Web.Tests;
public sealed class RegistrationTests public sealed class RegistrationTests
{ {
[Fact]
public async Task RegistrationOffersToResendAfterTheBackendReportsEmailDeliveryFailure()
{
var backend = new RegistrationBackend(failFirstDelivery: true);
await using var application = new WebApplicationFactory<Program>().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<string, string>
{
["__RequestVerificationToken"] = AntiforgeryToken(await registration.Content.ReadAsStringAsync(ct)),
["Email"] = "[email protected]",
["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=\"[email protected]\"", 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] [Fact]
public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword() public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword()
{ {
@@ -70,7 +108,7 @@ public sealed class RegistrationTests
Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString()); 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; } = []; public List<(string Path, JsonElement Body)> Requests { get; } = [];
@@ -84,6 +122,13 @@ public sealed class RegistrationTests
return new HttpResponseMessage(HttpStatusCode.NoContent); return new HttpResponseMessage(HttpStatusCode.NoContent);
Assert.Equal("/api/v1/auth/register", path); 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) return new HttpResponseMessage(HttpStatusCode.Created)
{ {
Content = new StringContent(""" Content = new StringContent("""
@@ -68,9 +68,15 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
new RegisterRequest(model.Email.Trim(), model.FirstName.Trim(), model.LastName.Trim()), ct); new RegisterRequest(model.Email.Trim(), model.FirstName.Trim(), model.LastName.Trim()), ct);
return View("RegisterDone", user.Email); 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)); ModelState.AddApiErrors(ex, typeof(RegisterViewModel));
return View(model); return View(model);
} }
@@ -195,7 +195,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
} }
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict) 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)) catch (ApiException ex) when (IsUserError(ex))
{ {
@@ -210,6 +210,9 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
private const string ConflictMessage = 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."; "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;
/// <summary> /// <summary>
/// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může /// 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 <see cref="ApiExceptionFilter"/>. /// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje <see cref="ApiExceptionFilter"/>.
@@ -223,8 +226,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
} }
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict) 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: ConflictError(ex));
return BackToDetail(id, error: ConflictMessage);
} }
catch (ApiException ex) when (IsUserError(ex)) catch (ApiException ex) when (IsUserError(ex))
{ {
@@ -1,6 +1,7 @@
@model RegisterViewModel @model RegisterViewModel
@{ @{
ViewData["Title"] = "Registrace"; ViewData["Title"] = "Registrace";
var resend = ViewData["VerificationEmailFailed"] is true;
} }
<section class="app-auth"> <section class="app-auth">
@@ -27,7 +28,7 @@
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span> <span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
</div> </div>
</div> </div>
<button type="submit" class="btn btn-primary w-100">Poslat ověřovací e-mail</button> <button type="submit" class="btn btn-primary w-100">@(resend ? "Poslat ověřovací e-mail znovu" : "Poslat ověřovací e-mail")</button>
</form> </form>
</div> </div>