From bd8eb65e56fca5480588f3201906735d4344b530 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Fri, 4 Dec 2026 18:25:30 +0100 Subject: [PATCH 1/9] backend: Add concurrency checks to admin user edits --- .../Controllers/AdminUsersController.cs | 1 + .../Infrastructure/AppExceptionHandler.cs | 2 +- .../src/Helpdesk.Application/Common/Errors.cs | 9 +- .../Notifications/PushDeviceService.cs | 6 ++ .../Helpdesk.Application/Users/UserDtos.cs | 7 +- .../Helpdesk.Application/Users/UserService.cs | 19 ++-- backend/src/Helpdesk.Domain/Users/User.cs | 1 + .../Persistence/Configurations.cs | 1 + .../Persistence/HelpdeskDbContext.cs | 15 ++++ .../AdminAccountLifecycleTests.cs | 88 ++++++++++++++++++- db/migrations/V006__user_row_version.sql | 2 + docs/navrh-aplikace.md | 4 +- web/Helpdesk.Web.Tests/AdminUsersTests.cs | 49 ++++++++++- web/Helpdesk.Web/Api/ApiException.cs | 9 +- web/Helpdesk.Web/Api/ApiModels.cs | 5 +- .../Controllers/AdminUsersController.cs | 13 +++ .../Models/AdminUsersViewModel.cs | 4 +- web/Helpdesk.Web/Views/AdminUsers/Form.cshtml | 4 + 18 files changed, 216 insertions(+), 23 deletions(-) create mode 100644 db/migrations/V006__user_row_version.sql diff --git a/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs b/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs index da9c664..c2a145a 100644 --- a/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AdminUsersController.cs @@ -36,6 +36,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current [HttpPut("{id:int}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status409Conflict)] public async Task Update(int id, SaveAdminUserRequest request, CancellationToken ct) { var result = await users.UpdateAsync(currentUser, id, request, ct); 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.Application/Common/Errors.cs b/backend/src/Helpdesk.Application/Common/Errors.cs index 56eaafb..551b8bd 100644 --- a/backend/src/Helpdesk.Application/Common/Errors.cs +++ b/backend/src/Helpdesk.Application/Common/Errors.cs @@ -1,9 +1,10 @@ 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) @@ -16,6 +17,12 @@ public sealed class ConflictException(string message) : AppException(message) 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; +} + public sealed class ForbiddenException(string message) : AppException(message) { public override int StatusCode => 403; 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..4b26976 100644 --- a/backend/src/Helpdesk.Application/Users/UserDtos.cs +++ b/backend/src/Helpdesk.Application/Users/UserDtos.cs @@ -49,14 +49,15 @@ public sealed record ChangeRoleRequest(string Role); public sealed record SetActiveRequest(bool IsActive); 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 { diff --git a/backend/src/Helpdesk.Application/Users/UserService.cs b/backend/src/Helpdesk.Application/Users/UserService.cs index 2f1b4a1..2601456 100644 --- a/backend/src/Helpdesk.Application/Users/UserService.cs +++ b/backend/src/Helpdesk.Application/Users/UserService.cs @@ -105,12 +105,18 @@ public sealed class UserService( public async Task UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct) { + if (request.RowVersion is null or < 0) + throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion)."); + await ValidateAsync(request, ct); 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 confirmationChanged = user.EmailConfirmed != confirmed; @@ -119,12 +125,13 @@ public sealed class UserService( ApplyProfile(user, request with { EmailConfirmed = 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 +193,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); diff --git a/backend/src/Helpdesk.Domain/Users/User.cs b/backend/src/Helpdesk.Domain/Users/User.cs index 28dbf13..b8b6105 100644 --- a/backend/src/Helpdesk.Domain/Users/User.cs +++ b/backend/src/Helpdesk.Domain/Users/User.cs @@ -26,6 +26,7 @@ public sealed class User : IHasCreatedAt 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}"; 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..f98a74d 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -42,6 +42,17 @@ 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 is not ( + nameof(User.FailedLoginCount) or nameof(User.LockoutUntil) or nameof(User.RowVersion)))) + { + var version = entry.Property(user => user.RowVersion); + version.CurrentValue = checked(version.OriginalValue + 1); + } + } + try { return await base.SaveChangesAsync(cancellationToken); @@ -58,6 +69,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/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs index 1b166f6..1c5ba6d 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs @@ -1,13 +1,17 @@ using System.Net; using System.Net.Http.Json; +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; @@ -39,7 +43,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); @@ -95,7 +103,7 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF 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 +120,80 @@ 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 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); + + const string newPassword = "Admin-reset-password"; + var edit = request with { Password = newPassword, RowVersion = created.RowVersion }; + 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() { @@ -150,4 +232,6 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF 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 sealed record CurrentSession(int Id, string TokenId) : ICurrentUser; } 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/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 04c935d..2a2f94c 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -725,7 +725,7 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal | 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í. | +| 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 | @@ -985,7 +985,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..0eb5d17 100644 --- a/web/Helpdesk.Web.Tests/AdminUsersTests.cs +++ b/web/Helpdesk.Web.Tests/AdminUsersTests.cs @@ -151,13 +151,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> { @@ -233,6 +237,38 @@ public sealed class AdminUsersTests (backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath)); } + [Fact] + public async Task StaleEditReloadsTheCurrentAccountAndShowsTheConflict() + { + 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 string AntiforgeryToken(string html) { var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; @@ -252,7 +288,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 +304,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 +318,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/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..a2c1670 100644 --- a/web/Helpdesk.Web/Api/ApiModels.cs +++ b/web/Helpdesk.Web/Api/ApiModels.cs @@ -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/Controllers/AdminUsersController.cs b/web/Helpdesk.Web/Controllers/AdminUsersController.cs index d00b392..8f42984 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,6 +163,12 @@ 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)) @@ -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/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/Views/AdminUsers/Form.cshtml b/web/Helpdesk.Web/Views/AdminUsers/Form.cshtml index 8ded610..ea8dcb4 100644 --- a/web/Helpdesk.Web/Views/AdminUsers/Form.cshtml +++ b/web/Helpdesk.Web/Views/AdminUsers/Form.cshtml @@ -16,6 +16,10 @@
+ @if (!isNew) + { + + }
-- 2.54.1 From ee5f1d3d101f644e6a57155fc7d0a29183e05ad6 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Fri, 4 Dec 2026 20:14:00 +0100 Subject: [PATCH 2/9] backend + web: Set passwords through email confirmation --- .../Controllers/AuthController.cs | 8 +- .../src/Helpdesk.Application/Auth/AuthDtos.cs | 18 +++- .../Helpdesk.Application/Auth/AuthService.cs | 19 ++-- .../Helpdesk.Application/Users/UserService.cs | 9 +- .../AdminAccountLifecycleTests.cs | 9 +- .../BackendFixture.cs | 4 +- .../EmailConfirmationTests.cs | 74 +++++++++++++++ docs/navrh-aplikace.md | 8 +- web/Helpdesk.Web.Tests/AdminUsersTests.cs | 9 -- web/Helpdesk.Web.Tests/AuthAndErrorsTests.cs | 4 +- web/Helpdesk.Web.Tests/RegistrationTests.cs | 95 +++++++++++++++++++ web/Helpdesk.Web.Tests/WebTestSession.cs | 8 ++ web/Helpdesk.Web/Api/ApiModels.cs | 4 +- web/Helpdesk.Web/Api/AuthApiClient.cs | 4 +- .../Controllers/AccountController.cs | 25 ++--- .../Controllers/AdminUsersController.cs | 4 +- web/Helpdesk.Web/Models/AccountModels.cs | 21 +--- .../Views/Account/ConfirmEmail.cshtml | 17 ++-- .../Views/Account/Register.cshtml | 13 +-- .../Views/Account/RegisterDone.cshtml | 2 +- .../Views/Account/ResetPassword.cshtml | 15 +-- .../Views/Account/_NewPasswordFields.cshtml | 13 +++ web/Helpdesk.Web/Views/AdminUsers/Form.cshtml | 8 +- 23 files changed, 281 insertions(+), 110 deletions(-) create mode 100644 backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs create mode 100644 web/Helpdesk.Web.Tests/RegistrationTests.cs create mode 100644 web/Helpdesk.Web/Views/Account/_NewPasswordFields.cshtml diff --git a/backend/src/Helpdesk.Api/Controllers/AuthController.cs b/backend/src/Helpdesk.Api/Controllers/AuthController.cs index 2552c93..3f8d2c9 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(); diff --git a/backend/src/Helpdesk.Application/Auth/AuthDtos.cs b/backend/src/Helpdesk.Application/Auth/AuthDtos.cs index 133653a..73ef51f 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); @@ -38,12 +38,22 @@ 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).Cascade(CascadeMode.Stop).ValidPassword() + .Must(password => Encoding.UTF8.GetByteCount(password) <= 72) + .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8."); + } +} + 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..f714ab8 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -19,6 +19,7 @@ public sealed class AuthService( IOptions registrationOptions, TimeProvider clock, IValidator registerValidator, + IValidator confirmEmailValidator, IValidator loginValidator, IValidator resetPasswordValidator) { @@ -35,11 +36,11 @@ public sealed class AuthService( 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 +52,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 revocation.StageRevokeAllAsync([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) @@ -75,7 +81,7 @@ public sealed class AuthService( 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 null || user.IsDeleted || user.EmailNormalized != account.EmailNormalized || user.PasswordHash.Length == 0) throw new UnauthorizedException(invalidCredentials); var now = clock.GetUtcNow().UtcDateTime; if (user.IsLockedOut(now)) @@ -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/Users/UserService.cs b/backend/src/Helpdesk.Application/Users/UserService.cs index 2601456..fa5edba 100644 --- a/backend/src/Helpdesk.Application/Users/UserService.cs +++ b/backend/src/Helpdesk.Application/Users/UserService.cs @@ -86,10 +86,11 @@ 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."); + if (request.EmailConfirmed && 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); + var passwordHash = request.EmailConfirmed ? passwordHasher.Hash(request.Password!) : ""; + var user = User.Create(request.Email, passwordHash, request.FirstName, request.LastName, role); ApplyProfile(user, request); user.SetActive(request.IsActive); @@ -119,6 +120,8 @@ public sealed class UserService( var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email); var confirmed = !emailChanged && request.EmailConfirmed; + 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); diff --git a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs index 1c5ba6d..c2a3533 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs @@ -56,7 +56,7 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF 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)); + 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)); @@ -97,7 +97,7 @@ 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); @@ -230,8 +230,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/BackendFixture.cs b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs index 521a837..0171ddd 100644 --- a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs +++ b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs @@ -75,9 +75,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/EmailConfirmationTests.cs b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs new file mode 100644 index 0000000..e339e20 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs @@ -0,0 +1,74 @@ +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.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 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(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); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, new string('č', 37)), Cancellation), + HttpStatusCode.BadRequest); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, Password), 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 LoginAsync(anonymous, address); + Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName)); + } +} diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 2a2f94c..b0de546 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. | @@ -655,8 +655,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 | +| 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,7 +724,7 @@ 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 | +| 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 | diff --git a/web/Helpdesk.Web.Tests/AdminUsersTests.cs b/web/Helpdesk.Web.Tests/AdminUsersTests.cs index 0eb5d17..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; @@ -213,7 +212,6 @@ public sealed class AdminUsersTests ["LastName"] = "Novák", ["Email"] = "novak@example.test", ["Role"] = UserRoles.Student, - ["Password"] = "Initial-password", ["IsActive"] = "true", ["EmailConfirmed"] = "false", }); @@ -269,13 +267,6 @@ public sealed class AdminUsersTests Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html); } - private static string AntiforgeryToken(string html) - { - var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; - Assert.NotEmpty(token); - return token; - } - private static WebApplicationFactory CreateApplication(AdminUsersBackend backend) => new WebApplicationFactory().WithWebHostBuilder(builder => builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient)) 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/RegistrationTests.cs b/web/Helpdesk.Web.Tests/RegistrationTests.cs new file mode 100644 index 0000000..3aea38f --- /dev/null +++ b/web/Helpdesk.Web.Tests/RegistrationTests.cs @@ -0,0 +1,95 @@ +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 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 : 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); + 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/ApiModels.cs b/web/Helpdesk.Web/Api/ApiModels.cs index a2c1670..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); 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..97cbd8f 100644 --- a/web/Helpdesk.Web/Controllers/AccountController.cs +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -66,39 +66,42 @@ 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) { // 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 +131,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 +149,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 8f42984..43a3b3c 100644 --- a/web/Helpdesk.Web/Controllers/AdminUsersController.cs +++ b/web/Helpdesk.Web/Controllers/AdminUsersController.cs @@ -171,8 +171,8 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller 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 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/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..db41f84 100644 --- a/web/Helpdesk.Web/Views/Account/Register.cshtml +++ b/web/Helpdesk.Web/Views/Account/Register.cshtml @@ -27,18 +27,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.

- + -- 2.54.1