U2 identity-mail-flows (backend): taal per gebruiker, uitnodigingsmail, opnieuw versturen, meldingen, stamp-controle

Kolommen Users.PreferredLanguage en Invitations.Language (additieve migratie). IdentityMailService
verstuurt uitnodiging, nieuwe link en meldingen bij deactiveren, heractiveren en rolwijziging;
een mailfout laat nooit een actie falen, het resultaat gaat mee in de respons naast de
kopieerbare link. Nieuwe actie resend-invite. De security stamp zit in het access token en wordt
vergeleken in de actief-controle: een wachtwoordwijziging beeindigt eerder uitgegeven access tokens,
de refresh geeft stil een nieuw token.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 19:10:44 +01:00
co-authored by Claude Sonnet 5.5
parent 2a0561a58e
commit 149f81a479
23 changed files with 1491 additions and 37 deletions
@@ -0,0 +1,166 @@
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Identity.Entities;
using SlpModularCms.Core.Identity.Models;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Tests.Email;
internal sealed class CapturingSender : IEmailSender
{
public List<OutgoingMail> Sent { get; } = [];
public MailSendResult Result { get; set; } = MailSendResult.Ok;
public bool Throw { get; set; }
public Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
{
if (Throw) throw new InvalidOperationException("boom with secret@example.org");
Sent.Add(mail);
return Task.FromResult(Result);
}
}
public class IdentityMailServiceTests
{
private readonly CapturingSender _sender = new();
private readonly ISiteSettingsService _settings = Substitute.For<ISiteSettingsService>();
public IdentityMailServiceTests() =>
_settings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("info@andreaslop.nl", "Andrea Slop Fotografie"));
private IdentityMailService Service(string smtpHost = "mail.example.nl", string defaultLanguage = "nl", int hours = 24, string logo = "/admin/brand-logo-on-light.png") =>
new(_sender, new MailTemplateRenderer(),
new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" })),
_settings,
Options.Create(new EmailOptions { LogoUrl = logo, BrandColor = "#5f6a58", Smtp = { Host = smtpHost } }),
Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" }),
Options.Create(new InvitationSettings { ExpiryHours = hours }),
NullLogger<IdentityMailService>.Instance);
[Fact]
public async Task Invitation_HasTheAdminLink_TheSiteSender_TheLogo_AndTheLifetime()
{
var result = await Service().SendInvitationAsync("new@example.org", "tok/en+1=", "nl", isNewLink: false);
result.Sent.Should().BeTrue();
var mail = _sender.Sent.Should().ContainSingle().Subject;
mail.ToAddress.Should().Be("new@example.org");
mail.FromAddress.Should().Be("info@andreaslop.nl");
mail.FromName.Should().Be("Andrea Slop Fotografie");
mail.Subject.Should().Be("Uitnodiging voor Andrea Slop Fotografie");
mail.HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D")
.And.Contain("https://test.andreaslop.nl/admin/brand-logo-on-light.png")
.And.Contain("24 uur").And.Contain("#5f6a58");
mail.TextBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D");
}
[Fact]
public async Task ANewLink_UsesTheNewLinkText_AndTheConfiguredLifetime()
{
await Service(hours: 48).SendInvitationAsync("new@example.org", "t", "nl", isNewLink: true);
var mail = _sender.Sent.Single();
mail.Subject.Should().StartWith("Nieuwe uitnodigingslink");
mail.HtmlBody.Should().Contain("48 uur");
}
[Theory]
[InlineData("en", "nl", "Invitation to")]
[InlineData(null, "en", "Invitation to")]
[InlineData(null, "nl", "Uitnodiging voor")]
[InlineData("nl", "en", "Uitnodiging voor")]
[InlineData("xx", "en", "Invitation to")]
public async Task TheLanguage_IsTheChosenOne_ElseTheSiteDefault(string? chosen, string siteDefault, string subjectStart)
{
await Service(defaultLanguage: siteDefault).SendInvitationAsync("new@example.org", "t", chosen, false);
_sender.Sent.Single().Subject.Should().StartWith(subjectStart);
}
[Fact]
public async Task WithoutAHost_NothingIsSent_AndItReportsDisabled()
{
var result = await Service(smtpHost: "").SendInvitationAsync("new@example.org", "t", null, false);
result.Should().Be(MailSendResult.Fail(MailSendResult.Disabled));
_sender.Sent.Should().BeEmpty();
Service(smtpHost: "").IsEnabled.Should().BeFalse();
}
[Fact]
public async Task ASenderFailure_IsPassedOnAsAValue()
{
_sender.Result = MailSendResult.Fail(MailSendResult.Timeout);
(await Service().SendInvitationAsync("new@example.org", "t", null, false)).Should().Be(MailSendResult.Fail(MailSendResult.Timeout));
}
[Fact]
public async Task AnExceptionAnywhere_NeverEscapes()
{
_sender.Throw = true;
var result = await Service().SendInvitationAsync("new@example.org", "t", null, false);
result.Should().Be(MailSendResult.Fail(MailSendResult.Unknown));
}
[Fact]
public async Task ARecipientWithoutAnAddress_IsRefused()
{
var result = await Service().SendAccountDeactivatedAsync(new ApplicationUser { Email = null });
result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected));
_sender.Sent.Should().BeEmpty();
}
[Fact]
public async Task Deactivation_IsAddressedToTheUser_InTheirLanguage_WithoutALink()
{
var user = new ApplicationUser { Email = "user@example.org", DisplayName = "Jan", PreferredLanguage = "en" };
await Service().SendAccountDeactivatedAsync(user);
var mail = _sender.Sent.Single();
mail.Subject.Should().Contain("deactivated");
mail.TextBody.Should().Contain("Hello Jan,").And.NotContain("https://");
}
[Fact]
public async Task Reactivation_LinksToTheLoginPage()
{
await Service().SendAccountReactivatedAsync(new ApplicationUser { Email = "user@example.org", DisplayName = "Jan" });
_sender.Sent.Single().HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/login");
}
[Fact]
public async Task RoleChange_NamesTheNewRole_InTheUsersLanguage()
{
await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "nl" }, "Administrator");
await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "en" }, "Administrator");
_sender.Sent[0].TextBody.Should().Contain("Beheerder");
_sender.Sent[1].TextBody.Should().Contain("Administrator");
}
[Fact]
public async Task AnAbsoluteLogoUrl_IsUsedAsIs_AndNoLogoMeansTheSiteName()
{
await Service(logo: "https://cdn.example.org/logo.png").SendInvitationAsync("a@example.org", "t", null, false);
await Service(logo: "").SendInvitationAsync("a@example.org", "t", null, false);
_sender.Sent[0].HtmlBody.Should().Contain("https://cdn.example.org/logo.png");
_sender.Sent[1].HtmlBody.Should().NotContain("<img");
}
[Theory]
[InlineData("https://t.nl", "/invite/complete?token=a", "https://t.nl/admin/invite/complete?token=a")]
[InlineData("https://t.nl/", "/login", "https://t.nl/admin/login")]
[InlineData("https://t.nl", "login", "https://t.nl/admin/login")]
public void BuildLink_PutsTheAdminBasePathBetweenSiteAndPath(string baseUrl, string path, string expected) =>
IdentityMailService.BuildLink(baseUrl, path).Should().Be(expected);
}
@@ -32,15 +32,26 @@ public class MigrationRoundTripTests
await db.Database.EnsureDeletedAsync();
await db.Database.MigrateAsync();
(await TableExists(db, "SiteSettings")).Should().BeTrue();
(await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeTrue();
(await ColumnExists(db, "Invitations", "Language")).Should().BeTrue();
var migrations = db.GetService<IMigrationsAssembly>().Migrations.Keys.OrderBy(k => k).ToList();
var previous = migrations[^2];
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(previous); // undo the newest
(await TableExists(db, "SiteSettings")).Should().BeFalse();
(await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeFalse();
(await ColumnExists(db, "Invitations", "Language")).Should().BeFalse();
(await TableExists(db, "SiteSettings")).Should().BeTrue(); // the one before stays
await migrator.MigrateAsync(); // and apply it again
(await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeTrue();
(await ColumnExists(db, "Invitations", "Language")).Should().BeTrue();
// The one before that can be undone as well (down to the schema without any of this feature).
await migrator.MigrateAsync(migrations[^3]);
(await TableExists(db, "SiteSettings")).Should().BeFalse();
await migrator.MigrateAsync();
(await TableExists(db, "SiteSettings")).Should().BeTrue();
}
finally
@@ -49,6 +60,14 @@ public class MigrationRoundTripTests
}
}
private static async Task<bool> ColumnExists(ApplicationDbContext db, string table, string column)
{
var rows = await db.Database
.SqlQuery<int>($"select count(*) as Value from information_schema.columns where table_schema = database() and table_name = {table} and column_name = {column}")
.ToListAsync();
return rows[0] > 0;
}
private static async Task<bool> TableExists(ApplicationDbContext db, string table)
{
var rows = await db.Database
@@ -79,7 +79,7 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
{
using var scope = _host.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive };
var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive, SecurityStamp = "stamp-1" };
db.Users.Add(user);
await db.SaveChangesAsync();
return user;
@@ -102,16 +102,17 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
await db.SaveChangesAsync();
}
private static string TokenFor(Guid userId)
private static string TokenFor(Guid userId, string? stamp = "stamp-1")
{
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Jwt.Secret));
var token = new JwtSecurityToken(
Jwt.Issuer,
Jwt.Audience,
[
new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
new Claim(ClaimTypes.Role, "Owner")
],
}.Concat(stamp is null ? [] : [new Claim(ActiveUserTokenValidation.StampClaim, stamp)]),
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
@@ -181,4 +182,44 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized);
}
private async Task SetStampAsync(Guid id, string stamp)
{
using var scope = _host.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await db.Users.SingleAsync(u => u.Id == id);
user.SecurityStamp = stamp;
await db.SaveChangesAsync();
}
[Fact]
public async Task APasswordChange_EndsTheAccessTokensIssuedBefore_ForGetAndPost()
{
var user = await AddUserAsync();
var token = TokenFor(user.Id, "stamp-1");
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK);
await SetStampAsync(user.Id, "stamp-2"); // what a password change or reset does
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized);
(await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.Unauthorized);
// A token issued after the change carries the new stamp and works.
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "stamp-2"))).Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task ATokenWithoutAStamp_IssuedBeforeThisCheckExisted_IsRefused()
{
var user = await AddUserAsync();
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, stamp: null))).Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ATokenWithAWrongStamp_IsRefused()
{
var user = await AddUserAsync();
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "someone-elses-stamp"))).Should().Be(HttpStatusCode.Unauthorized);
}
}
@@ -394,4 +394,32 @@ public class InvitationServiceTests
(await _service.RegenerateInvitationAsync(inv.Id)).Should().BeNull();
}
[Fact]
public async Task CreateInvitationAsync_StoresTheNormalisedLanguage()
{
var token = await _service.CreateInvitationAsync("lang@example.com", "User", "EN-gb");
(await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().Be("en");
(await _service.GetAllPendingInvitationsAsync()).Single().Language.Should().Be("en");
}
[Fact]
public async Task CreateInvitationAsync_IgnoresAnUnsupportedLanguage()
{
var token = await _service.CreateInvitationAsync("lang2@example.com", "User", "de");
(await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().BeNull();
}
[Fact]
public async Task CompleteInvitationAsync_CopiesTheInvitationLanguageToTheNewAccount()
{
var token = await _service.CreateInvitationAsync("lang3@example.com", "User", "en");
_userManager.CreateAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
await _service.CompleteInvitationAsync(token, "SafePassword123!", "Naam");
await _userManager.Received(1).CreateAsync(Arg.Is<ApplicationUser>(u => u.PreferredLanguage == "en"), "SafePassword123!");
}
}
@@ -0,0 +1,122 @@
using System.Net;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Identity.Authorization;
using SlpModularCms.Core.Identity.Entities;
using SlpModularCms.Core.Identity.Models;
using SlpModularCms.Core.Identity.Services;
namespace SlpModularCms.Core.Tests.Identity;
/// <summary>
/// The real chain end to end (real Identity password handling, real tokens from <see cref="AuthService"/>,
/// the real bearer check): a password change ends the access tokens issued before it, and the refresh
/// token then silently gives a new one that works.
/// </summary>
public class SessionEndsOnPasswordChangeTests : IAsyncLifetime
{
private static readonly JwtSettings Jwt = new()
{
Secret = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789",
Issuer = "test-issuer",
Audience = "test-audience",
ExpiryMinutes = 30
};
private readonly string _dbName = Guid.NewGuid().ToString();
private IHost _host = null!;
private HttpClient _client = null!;
public async Task InitializeAsync()
{
_host = await new HostBuilder().ConfigureWebHost(web =>
{
web.UseTestServer();
web.ConfigureServices(services =>
{
services.AddLogging();
services.AddRouting();
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(_dbName));
services.AddIdentityCore<ApplicationUser>().AddRoles<ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<JwtSettings>(o =>
{
o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes;
});
services.AddScoped<IAuthService, AuthService>();
services.AddAuthentication("Bearer").AddJwtBearer(o => o.UseCmsTokenValidation(JwtTokenValidation.Create(Jwt)));
services.AddAuthorization();
});
web.Configure(app =>
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(e => e.MapGet("/data", () => Results.Ok("secret")).RequireAuthorization());
});
}).StartAsync();
_client = _host.GetTestClient();
using var scope = _host.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var result = await users.CreateAsync(
new ApplicationUser { UserName = "owner@test.nl", Email = "owner@test.nl", IsActive = true, PreferredLanguage = "en" }, "Password1!");
result.Succeeded.Should().BeTrue(string.Join(",", result.Errors.Select(e => e.Code)));
}
public async Task DisposeAsync()
{
_client.Dispose();
await _host.StopAsync();
_host.Dispose();
}
private async Task<HttpStatusCode> GetAsync(string token)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/data");
request.Headers.Authorization = new("Bearer", token);
return (await _client.SendAsync(request)).StatusCode;
}
private async Task<T> InScope<T>(Func<IAuthService, Task<T>> action)
{
using var scope = _host.Services.CreateScope();
return await action(scope.ServiceProvider.GetRequiredService<IAuthService>());
}
[Fact]
public async Task ARealLoginToken_Works_AndCarriesTheUsersLanguage()
{
var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!"));
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK);
login.User.Language.Should().Be("en");
}
[Fact]
public async Task APasswordChange_EndsTheEarlierAccessToken_AndTheRefreshTokenGivesAWorkingNewOne()
{
var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!"));
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK);
await InScope(async a =>
{
await a.ChangePasswordAsync(login.User.Id, "Password1!", "Another-Pass2!");
return 0;
});
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.Unauthorized);
var refreshed = await InScope(a => a.RefreshTokenAsync(login.RefreshToken));
(await GetAsync(refreshed.AccessToken)).Should().Be(HttpStatusCode.OK);
}
}