From 663b872dc238c69f3f56c8b73547ae541bafbf06 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 28 Jul 2026 15:03:18 +0000 Subject: [PATCH] feat(auth): confirmation email + forgot/reset password #37: Email confirmation flow: - Nouveaux endpoints: POST /api/auth/confirm-email - Register envoie email de confirmation si SMTP configure + flag active - Login verifie EmailConfirmed si email.confirmation.required = true - Premier admin auto-confirme (evite chicken-and-egg) - Setting DB: email.confirmation.required (boolean) #38: Forgot/Reset password flow: - Nouveaux endpoints: POST /api/auth/forgot-password, POST /api/auth/reset-password - ForgotPassword genere token et envoie email via IEmailService - ResetPassword valide token et change le mot de passe - Pas de divulgation si l email n'existe pas Infrastructure email existante (IEmailService + SmtpClient) reutilisee. --- .../ConfirmEmail/ConfirmEmailCommand.cs | 6 ++ .../ConfirmEmail/ConfirmEmailHandler.cs | 55 ++++++++++++++++++ .../ForgotPassword/ForgotPasswordCommand.cs | 6 ++ .../ForgotPassword/ForgotPasswordHandler.cs | 55 ++++++++++++++++++ .../Auth/Commands/Login/LoginHandler.cs | 11 ++++ .../Auth/Commands/Register/RegisterHandler.cs | 40 +++++++++++++ .../ResetPassword/ResetPasswordCommand.cs | 6 ++ .../ResetPassword/ResetPasswordHandler.cs | 43 ++++++++++++++ src/Heimdall.Application/DTOs/AuthDto.cs | 4 ++ .../Controllers/AuthController.cs | 58 +++++++++++++++++++ .../Handlers/Auth/LoginHandlerTests.cs | 4 +- .../Auth/RegisterAdminHandlerTests.cs | 23 +++++++- .../Handlers/Auth/RegisterHandlerTests.cs | 4 +- 13 files changed, 312 insertions(+), 3 deletions(-) create mode 100644 src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailCommand.cs create mode 100644 src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailHandler.cs create mode 100644 src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordCommand.cs create mode 100644 src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordHandler.cs create mode 100644 src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordCommand.cs create mode 100644 src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordHandler.cs diff --git a/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailCommand.cs b/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailCommand.cs new file mode 100644 index 0000000..1588950 --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailCommand.cs @@ -0,0 +1,6 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Auth.Commands.ConfirmEmail; + +public record ConfirmEmailCommand(string UserId, string Token) : IRequest; diff --git a/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailHandler.cs b/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailHandler.cs new file mode 100644 index 0000000..4ab628e --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ConfirmEmail/ConfirmEmailHandler.cs @@ -0,0 +1,55 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using MediatR; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Application.Auth.Commands.ConfirmEmail; + +public class ConfirmEmailHandler : IRequestHandler +{ + private readonly UserManager _userManager; + private readonly ILogger _logger; + + public ConfirmEmailHandler(UserManager userManager, ILogger logger) + { + _userManager = userManager; + _logger = logger; + } + + public async Task Handle(ConfirmEmailCommand request, CancellationToken ct) + { + _logger.LogInformation("ConfirmEmail: UserId={UserId}", request.UserId); + + if (!Guid.TryParse(request.UserId, out var userId)) + { + _logger.LogWarning("ConfirmEmail: Invalid UserId format"); + return ServiceResult.Failure("Invalid user ID"); + } + + var user = await _userManager.FindByIdAsync(request.UserId).ConfigureAwait(false); + if (user is null) + { + _logger.LogWarning("ConfirmEmail: User not found UserId={UserId}", request.UserId); + return ServiceResult.NotFound("User not found"); + } + + if (user.EmailConfirmed) + { + _logger.LogInformation("ConfirmEmail: Already confirmed UserId={UserId}", request.UserId); + return ServiceResult.Success(); + } + + var decodedToken = Uri.UnescapeDataString(request.Token); + var result = await _userManager.ConfirmEmailAsync(user, decodedToken).ConfigureAwait(false); + if (!result.Succeeded) + { + var errors = string.Join(", ", result.Errors.Select(e => e.Description)); + _logger.LogWarning("ConfirmEmail: Failed UserId={UserId}: {Errors}", request.UserId, errors); + return ServiceResult.Failure(errors); + } + + _logger.LogInformation("ConfirmEmail: Confirmed successfully UserId={UserId}", request.UserId); + return ServiceResult.Success(); + } +} diff --git a/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordCommand.cs b/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordCommand.cs new file mode 100644 index 0000000..acf1f98 --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordCommand.cs @@ -0,0 +1,6 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Auth.Commands.ForgotPassword; + +public record ForgotPasswordCommand(string Email) : IRequest; diff --git a/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordHandler.cs b/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordHandler.cs new file mode 100644 index 0000000..9f20d24 --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ForgotPassword/ForgotPasswordHandler.cs @@ -0,0 +1,55 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using MediatR; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Application.Auth.Commands.ForgotPassword; + +public class ForgotPasswordHandler : IRequestHandler +{ + private readonly UserManager _userManager; + private readonly IEmailService _emailService; + private readonly ILogger _logger; + + public ForgotPasswordHandler( + UserManager userManager, + IEmailService emailService, + ILogger logger) + { + _userManager = userManager; + _emailService = emailService; + _logger = logger; + } + + public async Task Handle(ForgotPasswordCommand request, CancellationToken ct) + { + _logger.LogInformation("ForgotPassword: Email={Email}", request.Email); + + var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false); + // Ne pas divulguer si l'email existe ou pas + if (user is null || !await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false)) + { + _logger.LogInformation("ForgotPassword: No action for Email={Email} (not found or unconfirmed)", request.Email); + return ServiceResult.Success(); + } + + var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false); + var encodedToken = Uri.EscapeDataString(token); + + var resetLink = $"heimdall://reset-password?email={Uri.EscapeDataString(request.Email)}&token={encodedToken}"; + var body = $""" +

Réinitialisation de mot de passe

+

Vous avez demandé la réinitialisation de votre mot de passe Heimdall.

+

Cliquez sur le lien ci-dessous pour le réinitialiser :

+

Réinitialiser mon mot de passe

+

Ce lien est valable 24h. Si vous n'avez pas fait cette demande, ignorez cet email.

+ """; + + await _emailService.SendEmailAsync(request.Email, "Réinitialisation de mot de passe Heimdall", body, ct).ConfigureAwait(false); + + _logger.LogInformation("ForgotPassword: Reset link sent to Email={Email}", request.Email); + return ServiceResult.Success(); + } +} diff --git a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs index a415803..b98223a 100644 --- a/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs @@ -16,6 +16,7 @@ public class LoginHandler : IRequestHandler _logger; public LoginHandler( @@ -24,6 +25,7 @@ public class LoginHandler : IRequestHandler logger) { _userManager = userManager; @@ -31,6 +33,7 @@ public class LoginHandler : IRequestHandler.Unauthorized("Invalid email or password"); } + // Vérifier la confirmation email si requise + var emailConfirmRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false); + if (string.Equals(emailConfirmRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) + { + _logger.LogWarning("Login: Email not confirmed Email={Email}", request.Email); + return ServiceResult.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403); + } + _logger.LogInformation("Login: Success Email={Email}", request.Email); return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false); } diff --git a/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs b/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs index d1fe08e..5ea9ba7 100644 --- a/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Register/RegisterHandler.cs @@ -15,6 +15,7 @@ public class RegisterHandler : IRequestHandler _logger; public RegisterHandler( @@ -22,12 +23,14 @@ public class RegisterHandler : IRequestHandler logger) { _userManager = userManager; _jwtService = jwtService; _rolePermissionService = rolePermissionService; _authData = authData; + _emailService = emailService; _logger = logger; } @@ -76,6 +79,9 @@ public class RegisterHandler : IRequestHandlerBienvenue sur Heimdall +

Merci de vous être inscrit. Veuillez confirmer votre adresse email en cliquant sur le lien ci-dessous :

+

Confirmer mon email

+

Ce lien est valable 24h.

+ """; + + await _emailService.SendEmailAsync(user.Email!, "Confirmez votre email - Heimdall", body, ct).ConfigureAwait(false); + _logger.LogInformation("Register: Confirmation email sent to {Email}", user.Email); + } + catch (Exception ex) + { + // L'echec de l envoi d email ne bloque pas l inscription + _logger.LogWarning(ex, "Register: Failed to send confirmation email to {Email}", user.Email); + } + } } diff --git a/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordCommand.cs b/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordCommand.cs new file mode 100644 index 0000000..e81c19f --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordCommand.cs @@ -0,0 +1,6 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Auth.Commands.ResetPassword; + +public record ResetPasswordCommand(string Email, string Token, string NewPassword) : IRequest; diff --git a/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordHandler.cs b/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordHandler.cs new file mode 100644 index 0000000..afeeae8 --- /dev/null +++ b/src/Heimdall.Application/Auth/Commands/ResetPassword/ResetPasswordHandler.cs @@ -0,0 +1,43 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using MediatR; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Application.Auth.Commands.ResetPassword; + +public class ResetPasswordHandler : IRequestHandler +{ + private readonly UserManager _userManager; + private readonly ILogger _logger; + + public ResetPasswordHandler(UserManager userManager, ILogger logger) + { + _userManager = userManager; + _logger = logger; + } + + public async Task Handle(ResetPasswordCommand request, CancellationToken ct) + { + _logger.LogInformation("ResetPassword: Email={Email}", request.Email); + + var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false); + if (user is null) + { + _logger.LogWarning("ResetPassword: User not found Email={Email}", request.Email); + return ServiceResult.NotFound("User not found"); + } + + var decodedToken = Uri.UnescapeDataString(request.Token); + var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword).ConfigureAwait(false); + if (!result.Succeeded) + { + var errors = string.Join(", ", result.Errors.Select(e => e.Description)); + _logger.LogWarning("ResetPassword: Failed Email={Email}: {Errors}", request.Email, errors); + return ServiceResult.Failure(errors); + } + + _logger.LogInformation("ResetPassword: Success Email={Email}", request.Email); + return ServiceResult.Success(); + } +} diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs index e639c65..f130b4c 100644 --- a/src/Heimdall.Application/DTOs/AuthDto.cs +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -44,3 +44,7 @@ public record LogoutRequest(string RefreshToken); public record Enable2faResponse( string SharedKey, string QrCodeUri); + +public record ConfirmEmailRequest(string UserId, string Token); +public record ForgotPasswordRequest(string Email); +public record ResetPasswordRequest(string Email, string Token, string NewPassword); diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index 2cb4079..7823008 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -5,6 +5,9 @@ using Heimdall.Application.Auth.Commands.Verify2fa; using Heimdall.Application.Auth.Commands.RefreshToken; using Heimdall.Application.Auth.Commands.ChangePassword; using Heimdall.Application.Auth.Commands.RegisterAdmin; +using Heimdall.Application.Auth.Commands.ConfirmEmail; +using Heimdall.Application.Auth.Commands.ForgotPassword; +using Heimdall.Application.Auth.Commands.ResetPassword; using Heimdall.Application.Auth.Commands.Enable2fa; using Heimdall.Application.Auth.Commands.Disable2fa; using Heimdall.Application.Auth.Commands.Logout; @@ -222,6 +225,61 @@ public class AuthController : ControllerBase return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } + // ─── Email Confirmation ─────────────────────────────────────── + + /// Confirm email address with token. + [AllowAnonymous] + [HttpPost("confirm-email")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ConfirmEmail([FromBody] ConfirmEmailRequest request, CancellationToken ct) + { + _logger.LogInformation("ConfirmEmail attempt for UserId={UserId}", request.UserId); + var result = await _mediator.Send(new ConfirmEmailCommand(request.UserId, request.Token), ct); + + if (result.IsSuccess) + { + _logger.LogInformation("Email confirmed for UserId={UserId}", request.UserId); + return Ok(new { message = "Email confirmed successfully" }); + } + + _logger.LogWarning("Email confirmation failed for UserId={UserId}: {Error}", request.UserId, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + // ─── Forgot & Reset Password ────────────────────────────────── + + /// Send password reset link via email. + [AllowAnonymous] + [HttpPost("forgot-password")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task ForgotPassword([FromBody] ForgotPasswordRequest request, CancellationToken ct) + { + _logger.LogInformation("ForgotPassword request for {Email}", request.Email); + await _mediator.Send(new ForgotPasswordCommand(request.Email), ct); + return Ok(new { message = "If the email exists, a reset link has been sent." }); + } + + /// Reset password with token. + [AllowAnonymous] + [HttpPost("reset-password")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct) + { + _logger.LogInformation("ResetPassword attempt for {Email}", request.Email); + var result = await _mediator.Send(new ResetPasswordCommand(request.Email, request.Token, request.NewPassword), ct); + + if (result.IsSuccess) + { + _logger.LogInformation("Password reset successfully for {Email}", request.Email); + return Ok(new { message = "Password reset successfully" }); + } + + _logger.LogWarning("Password reset failed for {Email}: {Error}", request.Email, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + /// Logout — revoke the current refresh token. [Authorize] [HttpPost("logout")] diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs index 11d4bd6..f90e8a4 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs @@ -18,6 +18,7 @@ public class LoginHandlerTests private readonly IRolePermissionService _rolePermissionService; private readonly ILogger _logger; private readonly IUserRepository _userRepository; + private readonly IAuthDataService _authData; private readonly LoginHandler _handler; public LoginHandlerTests() @@ -30,7 +31,8 @@ public class LoginHandlerTests _rolePermissionService = Substitute.For(); _logger = Substitute.For>(); _userRepository = Substitute.For(); - _handler = new LoginHandler(_userManager, _signInService, _jwtService, _rolePermissionService, _userRepository, _logger); + _authData = Substitute.For(); + _handler = new LoginHandler(_userManager, _signInService, _jwtService, _rolePermissionService, _userRepository, _authData, _logger); } [Fact] diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs index 279c20e..181e31a 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs @@ -13,6 +13,7 @@ public class RegisterAdminHandlerTests private readonly UserManager _userManager; private readonly IJwtService _jwtService; private readonly IRolePermissionService _rolePermissionService; + private readonly IAuthDataService _authData; private readonly ILogger _logger; private readonly RegisterAdminHandler _handler; @@ -23,13 +24,16 @@ public class RegisterAdminHandlerTests _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); _jwtService = Substitute.For(); _rolePermissionService = Substitute.For(); + _authData = Substitute.For(); _logger = Substitute.For>(); - _handler = new RegisterAdminHandler(_userManager, _jwtService, _rolePermissionService, _logger); + _handler = new RegisterAdminHandler(_authData, _userManager, _jwtService, _rolePermissionService, _logger); } [Fact] public async Task Register_admin_should_create_user_with_admin_role() { + _authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any()) + .Returns("true"); _userManager.FindByEmailAsync("admin@test.com").Returns((AppUser?)null); _userManager.CreateAsync(Arg.Any(), "password").Returns(IdentityResult.Success); _userManager.AddToRoleAsync(Arg.Any(), Arg.Any()).Returns(IdentityResult.Success); @@ -49,6 +53,8 @@ public class RegisterAdminHandlerTests [Fact] public async Task Register_admin_with_existing_email_should_return_conflict() { + _authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any()) + .Returns("true"); _userManager.FindByEmailAsync("existing@test.com").Returns(new AppUser()); var result = await _handler.Handle( @@ -58,9 +64,24 @@ public class RegisterAdminHandlerTests result.StatusCode.ShouldBe(409); } + [Fact] + public async Task Register_admin_when_disabled_should_return_403() + { + _authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any()) + .Returns("false"); + + var result = await _handler.Handle( + new RegisterAdminCommand("test@test.com", "TestPwd123!", "Test"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(403); + } + [Fact] public async Task Register_admin_when_creation_fails_should_return_error() { + _authData.GetSettingValueAsync("auth.admin-registration.enabled", Arg.Any()) + .Returns("true"); _userManager.FindByEmailAsync("fail@test.com").Returns((AppUser?)null); _userManager.CreateAsync(Arg.Any(), Arg.Any()) .Returns(IdentityResult.Failed(new IdentityError { Description = "Password too weak" })); diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs index 2b128d8..93cb16b 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs @@ -14,6 +14,7 @@ public class RegisterHandlerTests private readonly IJwtService _jwtService; private readonly IRolePermissionService _rolePermissionService; private readonly IAuthDataService _authData; + private readonly IEmailService _emailService; private readonly ILogger _logger; private readonly RegisterHandler _handler; @@ -25,8 +26,9 @@ public class RegisterHandlerTests _jwtService = Substitute.For(); _rolePermissionService = Substitute.For(); _authData = Substitute.For(); + _emailService = Substitute.For(); _logger = Substitute.For>(); - _handler = new RegisterHandler(_userManager, _jwtService, _rolePermissionService, _authData, _logger); + _handler = new RegisterHandler(_userManager, _jwtService, _rolePermissionService, _authData, _emailService, _logger); } [Fact]