Files
slp-modular-cms/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs
T
SluijsensandClaude Sonnet 5.5 149f81a479 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>
2026-11-08 19:10:44 +01:00

167 lines
7.1 KiB
C#

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);
}