Uitnodigingen: naam opslaan en hetzelfde e-mailadres opnieuw kunnen uitnodigen
De naam uit het uitnodigingsformulier werd niet opgeslagen (profiel en verwijder-dialoog toonden het e-mailadres). Een geaccepteerde uitnodiging bleef na het verwijderen van de gebruiker staan en blokkeerde het adres; het conflict gaf een 500. Nu 409 met een specifieke melding en opruimen van verouderde uitnodigingen. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -144,11 +144,11 @@ public class InvitationServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePendingInvitationsByEmailAsync_ShouldRemoveMatchingInvitations()
|
||||
public async Task DeleteInvitationsByEmailAsync_ShouldRemoveMatchingInvitations()
|
||||
{
|
||||
await _service.CreateInvitationAsync("invited@example.com", "User");
|
||||
|
||||
await _service.DeletePendingInvitationsByEmailAsync("invited@example.com");
|
||||
await _service.DeleteInvitationsByEmailAsync("invited@example.com");
|
||||
|
||||
var (isPending, _) = await _service.GetPendingInvitationByEmailAsync("invited@example.com");
|
||||
isPending.Should().BeFalse();
|
||||
@@ -208,4 +208,93 @@ public class InvitationServiceTests
|
||||
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteInvitationAsync_StoresTheChosenNameAsDisplayName()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("named@example.com", "User");
|
||||
_userManager.CreateAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
|
||||
|
||||
await _service.CompleteInvitationAsync(token, "SafePassword123!", " Bryan ");
|
||||
|
||||
await _userManager.Received(1).CreateAsync(
|
||||
Arg.Is<ApplicationUser>(u => u.DisplayName == "Bryan"), "SafePassword123!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteInvitationAsync_WithoutName_LeavesDisplayNameEmpty()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("noname@example.com", "User");
|
||||
_userManager.CreateAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
|
||||
|
||||
await _service.CompleteInvitationAsync(token, "SafePassword123!", " ");
|
||||
|
||||
await _userManager.Received(1).CreateAsync(Arg.Is<ApplicationUser>(u => u.DisplayName == null), "SafePassword123!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_AfterAcceptedInvitationAndDeletedUser_CanInviteSameAddressAgain()
|
||||
{
|
||||
// The reported case: invite, accept, delete the account, invite the same address again.
|
||||
var token = await _service.CreateInvitationAsync("again@example.com", "User");
|
||||
_userManager.CreateAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
|
||||
await _service.CompleteInvitationAsync(token, "SafePassword123!", "Again");
|
||||
// The user is deleted: FindByEmailAsync no longer finds it, the accepted invitation remains.
|
||||
_userManager.FindByEmailAsync("again@example.com").Returns((ApplicationUser?)null);
|
||||
|
||||
var newToken = await _service.CreateInvitationAsync("again@example.com", "Administrator");
|
||||
|
||||
newToken.Should().NotBe(token);
|
||||
(await _context.Invitations.CountAsync(i => i.Email == "again@example.com")).Should().Be(1);
|
||||
(await _service.GetPendingInvitationByEmailAsync("again@example.com")).IsPending.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_AfterExpiredInvitation_ReplacesIt()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("late@example.com", "User");
|
||||
var old = await _context.Invitations.SingleAsync(i => i.Token == token);
|
||||
old.ExpiryDate = DateTimeOffset.UtcNow.AddDays(-1);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var newToken = await _service.CreateInvitationAsync("late@example.com", "User");
|
||||
|
||||
newToken.Should().NotBe(token);
|
||||
(await _context.Invitations.CountAsync(i => i.Email == "late@example.com")).Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_WhileOpenInvitationExists_SaysSo()
|
||||
{
|
||||
await _service.CreateInvitationAsync("open@example.com", "User");
|
||||
|
||||
var act = () => _service.CreateInvitationAsync("OPEN@example.com", "User");
|
||||
|
||||
(await act.Should().ThrowAsync<InvitationOrUserAlreadyExistsException>())
|
||||
.WithMessage("*openstaande uitnodiging*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_ForExistingUser_SaysSo()
|
||||
{
|
||||
_userManager.FindByEmailAsync("here@example.com").Returns(new ApplicationUser { Email = "here@example.com" });
|
||||
|
||||
var act = () => _service.CreateInvitationAsync("here@example.com", "User");
|
||||
|
||||
(await act.Should().ThrowAsync<InvitationOrUserAlreadyExistsException>())
|
||||
.WithMessage("*gebruiker*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteInvitationsByEmailAsync_AlsoRemovesAcceptedInvitations()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("gone@example.com", "User");
|
||||
var inv = await _context.Invitations.SingleAsync(i => i.Token == token);
|
||||
inv.IsAccepted = true;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
await _service.DeleteInvitationsByEmailAsync("gone@example.com");
|
||||
|
||||
(await _context.Invitations.AnyAsync(i => i.Email == "gone@example.com")).Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,9 @@ public class GlobalExceptionHandler : IExceptionHandler
|
||||
{
|
||||
Status = statusCode,
|
||||
Title = title,
|
||||
Detail = _env.IsDevelopment() ? exception.ToString() : "Er is een interne serverfout opgetreden.",
|
||||
Detail = exception is InvitationOrUserAlreadyExistsException
|
||||
? exception.Message // Dutch, written for the user, contains no internals
|
||||
: _env.IsDevelopment() ? exception.ToString() : "Er is een interne serverfout opgetreden.",
|
||||
Instance = httpContext.Request.Path
|
||||
};
|
||||
|
||||
@@ -74,6 +76,7 @@ public class GlobalExceptionHandler : IExceptionHandler
|
||||
return exception switch
|
||||
{
|
||||
UnauthorizedException => (StatusCodes.Status401Unauthorized, "Unauthorized"),
|
||||
InvitationOrUserAlreadyExistsException => (StatusCodes.Status409Conflict, "Conflict"),
|
||||
_ => (StatusCodes.Status500InternalServerError, "Internal Server Error")
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace SlpModularCms.Core.Identity.Models;
|
||||
[ExcludeFromCodeCoverage] public record CreateOwnerRequest(string Name, string Email, string Password);
|
||||
[ExcludeFromCodeCoverage] public record LoginRequest(string Email, string Password);
|
||||
[ExcludeFromCodeCoverage] public record InviteUserRequest(string Email, string Role);
|
||||
[ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password);
|
||||
[ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null);
|
||||
[ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole);
|
||||
[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email);
|
||||
[ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword);
|
||||
|
||||
@@ -20,7 +20,7 @@ public interface IInvitationService
|
||||
/// <summary>
|
||||
/// Voltooit de uitnodiging door een gebruiker aan te maken met het opgegeven wachtwoord.
|
||||
/// </summary>
|
||||
Task CompleteInvitationAsync(string token, string password);
|
||||
Task CompleteInvitationAsync(string token, string password, string? name = null);
|
||||
|
||||
/// <summary>
|
||||
/// Geeft de pending uitnodiging voor een e-mailadres terug, of (false, null) als er geen is.
|
||||
@@ -28,9 +28,9 @@ public interface IInvitationService
|
||||
Task<(bool IsPending, string? Token)> GetPendingInvitationByEmailAsync(string email);
|
||||
|
||||
/// <summary>
|
||||
/// Verwijdert alle pending (niet-geaccepteerde) uitnodigingen voor een e-mailadres.
|
||||
/// Verwijdert alle uitnodigingen (ook geaccepteerde en verlopen) voor een e-mailadres, zodat het adres opnieuw uitgenodigd kan worden.
|
||||
/// </summary>
|
||||
Task DeletePendingInvitationsByEmailAsync(string email);
|
||||
Task DeleteInvitationsByEmailAsync(string email);
|
||||
|
||||
/// <summary>
|
||||
/// Geeft alle actieve (niet-geaccepteerde, niet-verlopen) uitnodigingen terug.
|
||||
|
||||
@@ -21,14 +21,31 @@ public class InvitationService : IInvitationService
|
||||
|
||||
public async Task<string> CreateInvitationAsync(string email, string role)
|
||||
{
|
||||
var invitationForEmail = await _context.Invitations.FirstOrDefaultAsync(x => x.Email == email);
|
||||
var user = await _userManager.FindByEmailAsync(email);
|
||||
|
||||
if (invitationForEmail != null || user != null)
|
||||
if (user != null)
|
||||
{
|
||||
throw new InvitationOrUserAlreadyExistsException("Een uitnodiging of gebruiker voor dit e-mailadres bestaat al.");
|
||||
throw new InvitationOrUserAlreadyExistsException("Er bestaat al een gebruiker met dit e-mailadres.");
|
||||
}
|
||||
|
||||
|
||||
var normalized = email.ToLower();
|
||||
var invitationsForEmail = await _context.Invitations
|
||||
.Where(x => x.Email.ToLower() == normalized)
|
||||
.ToListAsync();
|
||||
|
||||
if (invitationsForEmail.Any(i => !i.IsAccepted && !i.IsExpired))
|
||||
{
|
||||
throw new InvitationOrUserAlreadyExistsException(
|
||||
"Er staat al een openstaande uitnodiging voor dit e-mailadres.");
|
||||
}
|
||||
|
||||
// What is left is stale: an expired invitation, or an accepted one whose user no longer
|
||||
// exists (the account was deleted). Neither can be used again, and an accepted one used to
|
||||
// block re-inviting the same address for good.
|
||||
if (invitationsForEmail.Count > 0)
|
||||
{
|
||||
_context.Invitations.RemoveRange(invitationsForEmail);
|
||||
}
|
||||
|
||||
var token = GenerateSecureToken();
|
||||
var invitation = new Invitation
|
||||
{
|
||||
@@ -51,7 +68,7 @@ public class InvitationService : IInvitationService
|
||||
return invitation != null && !invitation.IsAccepted && !invitation.IsExpired;
|
||||
}
|
||||
|
||||
public async Task CompleteInvitationAsync(string token, string password)
|
||||
public async Task CompleteInvitationAsync(string token, string password, string? name = null)
|
||||
{
|
||||
var invitation = await _context.Invitations.FirstOrDefaultAsync(i => i.Token == token);
|
||||
if (invitation == null || invitation.IsAccepted || invitation.IsExpired)
|
||||
@@ -63,6 +80,7 @@ public class InvitationService : IInvitationService
|
||||
{
|
||||
UserName = invitation.Email,
|
||||
Email = invitation.Email,
|
||||
DisplayName = string.IsNullOrWhiteSpace(name) ? null : name.Trim(),
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
@@ -85,10 +103,10 @@ public class InvitationService : IInvitationService
|
||||
return invitation is null ? (false, null) : (true, invitation.Token);
|
||||
}
|
||||
|
||||
public async Task DeletePendingInvitationsByEmailAsync(string email)
|
||||
public async Task DeleteInvitationsByEmailAsync(string email)
|
||||
{
|
||||
var invitations = await _context.Invitations
|
||||
.Where(i => i.Email == email && !i.IsAccepted)
|
||||
.Where(i => i.Email.ToLower() == email.ToLower())
|
||||
.ToListAsync();
|
||||
if (invitations.Count > 0)
|
||||
{
|
||||
|
||||
@@ -119,10 +119,10 @@ public class InvitationControllerTests : IDisposable
|
||||
{
|
||||
var controller = CreateController();
|
||||
|
||||
var result = await controller.Complete(new CompleteSetupRequest("some-token", "Password1!"));
|
||||
var result = await controller.Complete(new CompleteSetupRequest("some-token", "Password1!", "Bryan"));
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { message = "Account succesvol ingesteld. Je kunt nu inloggen." });
|
||||
await _invitationService.Received(1).CompleteInvitationAsync("some-token", "Password1!");
|
||||
await _invitationService.Received(1).CompleteInvitationAsync("some-token", "Password1!", "Bryan");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +267,7 @@ public class UsersControllerTests : IDisposable
|
||||
public async Task DeleteUser_ReturnsNoContent_WhenDeletingOtherUser()
|
||||
{
|
||||
var user = await CreateUser("other@test.com");
|
||||
_invitationService.DeletePendingInvitationsByEmailAsync(Arg.Any<string>()).Returns(Task.CompletedTask);
|
||||
_invitationService.DeleteInvitationsByEmailAsync(Arg.Any<string>()).Returns(Task.CompletedTask);
|
||||
|
||||
var result = await CreateController("admin@test.com").DeleteUser(user.Id);
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ public class InvitationController : ControllerBase
|
||||
[HttpPost("complete")]
|
||||
public async Task<IActionResult> Complete([FromBody] CompleteSetupRequest request)
|
||||
{
|
||||
await _invitationService.CompleteInvitationAsync(request.Token, request.Password);
|
||||
await _invitationService.CompleteInvitationAsync(request.Token, request.Password, request.Name);
|
||||
return Ok(new { message = "Account succesvol ingesteld. Je kunt nu inloggen." });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,7 +232,7 @@ public class UsersController : ControllerBase
|
||||
return BadRequest(new { detail = "At least one Owner must remain." });
|
||||
}
|
||||
|
||||
await _invitationService.DeletePendingInvitationsByEmailAsync(target.Email ?? string.Empty);
|
||||
await _invitationService.DeleteInvitationsByEmailAsync(target.Email ?? string.Empty);
|
||||
|
||||
var result = await _userManager.DeleteAsync(target);
|
||||
if (!result.Succeeded)
|
||||
|
||||
Reference in New Issue
Block a user