backend + web: Set passwords through email confirmation
This commit is contained in:
1 parent
bd8eb65e56
commit
ee5f1d3d10
23 files changed
+281
-110
No files matched your search
@@ -15,8 +15,8 @@ namespace Helpdesk.Api.Controllers;
|
||||
[Produces("application/json")]
|
||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
{
|
||||
/// <summary>Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
||||
/// <remarks>Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit.</remarks>
|
||||
/// <summary>Registrace e-mailem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
||||
/// <remarks>Heslo se nastavuje až po otevření ověřovacího odkazu z e-mailu.</remarks>
|
||||
[HttpPost("register")]
|
||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
@@ -28,11 +28,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
return Created($"/{ApiRoutes.V1}/users/me", user);
|
||||
}
|
||||
|
||||
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</summary>
|
||||
/// <summary>Ověří e-mail jednorázovým tokenem a nastaví heslo k účtu.</summary>
|
||||
[HttpPost("confirm-email")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ConfirmEmail(EmailTokenRequest request, CancellationToken ct)
|
||||
public async Task<IActionResult> ConfirmEmail(ConfirmEmailRequest request, CancellationToken ct)
|
||||
{
|
||||
await auth.ConfirmEmailAsync(request, ct);
|
||||
return NoContent();
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
|
||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||
|
||||
/// <summary>Token z odkazu v e-mailu (ověření e-mailu).</summary>
|
||||
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<RegisterRequest
|
||||
public RegisterRequestValidator()
|
||||
{
|
||||
RuleFor(x => 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<ConfirmEmailRequest>
|
||||
{
|
||||
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<LoginRequest>
|
||||
{
|
||||
public LoginRequestValidator()
|
||||
|
||||
@@ -19,6 +19,7 @@ public sealed class AuthService(
|
||||
IOptions<RegistrationOptions> registrationOptions,
|
||||
TimeProvider clock,
|
||||
IValidator<RegisterRequest> registerValidator,
|
||||
IValidator<ConfirmEmailRequest> confirmEmailValidator,
|
||||
IValidator<LoginRequest> loginValidator,
|
||||
IValidator<ResetPasswordRequest> 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<bool> 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<AuthResponse> 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;
|
||||
|
||||
@@ -86,10 +86,11 @@ public sealed class UserService(
|
||||
public async Task<AdminUserDetailsDto> 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);
|
||||
|
||||
@@ -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<AuthResponse>(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("[email protected]", "Test", "Uživatel", null,
|
||||
"STUDENT", true, false, false, Password);
|
||||
"STUDENT", true, false, false, null);
|
||||
var created = await ReadAsync<AdminUserDetailsDto>(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;
|
||||
}
|
||||
@@ -75,9 +75,9 @@ public sealed class BackendFixture : IAsyncLifetime
|
||||
{
|
||||
var address = $"{Guid.NewGuid():N}@student.example.test";
|
||||
var user = await ReadAsync<UserDto>(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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<BackendFixture>
|
||||
{
|
||||
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 = "[email protected]";
|
||||
var user = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register,
|
||||
new RegisterRequest(address, "Jan", "Novák"), Cancellation), HttpStatusCode.Created);
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
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<HelpdeskDbContext>();
|
||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||
const string address = "[email protected]";
|
||||
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<ITokenService>().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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user