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
@@ -28,6 +28,7 @@ public static class EmailServiceCollectionExtensions
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
services.TryAddScoped<ISiteSettingsService, SiteSettingsService>();
services.TryAddScoped<IIdentityMailService, IdentityMailService>();
return services;
}
@@ -0,0 +1,105 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Identity.Entities;
using SlpModularCms.Core.Identity.Models;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Builds and sends the identity mails (invitation, new link, notices). One orchestration point so a
/// controller never knows about templates, languages, links or the sender.
/// </summary>
public interface IIdentityMailService
{
/// <summary>True when this site can send mail (an SMTP host is configured).</summary>
bool IsEnabled { get; }
Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default);
Task<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default);
Task<MailSendResult> SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default);
Task<MailSendResult> SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default);
}
public sealed class IdentityMailService(
IEmailSender sender,
IMailTemplateRenderer renderer,
ILanguageResolver languages,
ISiteSettingsService siteSettings,
IOptions<EmailOptions> email,
IOptions<AppMailOptions> app,
IOptions<InvitationSettings> invitation,
ILogger<IdentityMailService> logger) : IIdentityMailService
{
public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host);
public Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default) =>
SendAsync(
isNewLink ? MailKind.NewInvitationLink : MailKind.Invitation,
email,
language,
recipientName: null,
actionPath: "/invite/complete?token=" + Uri.EscapeDataString(token),
validForMinutes: invitation.Value.ExpiryHours * 60,
detail: null,
ct);
public Task<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default) =>
SendAsync(MailKind.AccountDeactivated, user.Email, user.PreferredLanguage, user.DisplayName, null, null, null, ct);
public Task<MailSendResult> SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default) =>
SendAsync(MailKind.AccountReactivated, user.Email, user.PreferredLanguage, user.DisplayName, "/login", null, null, ct);
public Task<MailSendResult> SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default) =>
SendAsync(MailKind.RoleChanged, user.Email, user.PreferredLanguage, user.DisplayName, null, null, newRole, ct);
private async Task<MailSendResult> SendAsync(
MailKind kind, string? to, string? language, string? recipientName, string? actionPath,
int? validForMinutes, string? detail, CancellationToken ct)
{
if (!IsEnabled) return MailSendResult.Fail(MailSendResult.Disabled);
try
{
if (string.IsNullOrWhiteSpace(to)) return MailSendResult.Fail(MailSendResult.Rejected);
var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(ct);
var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/');
var model = new MailModel(
SiteName: fromName,
RecipientName: recipientName,
ActionUrl: actionPath is null ? null : BuildLink(baseUrl, actionPath),
ValidForMinutes: validForMinutes,
Detail: detail,
LogoUrl: ResolveLogo(baseUrl, email.Value.LogoUrl),
BrandColor: string.IsNullOrWhiteSpace(email.Value.BrandColor) ? null : email.Value.BrandColor);
var rendered = renderer.Render(kind, languages.Resolve(language), model);
var result = await sender.SendAsync(
new OutgoingMail(to, rendered.Subject, rendered.Html, rendered.Text, fromAddress, fromName), ct);
// Recipient DOMAIN only: never the address, the link or the token.
var domain = to.Contains('@') ? to[(to.LastIndexOf('@') + 1)..] : "?";
if (result.Sent)
logger.LogInformation("identity_mail_sent kind={Kind} recipient_domain={Domain}", kind, domain);
else
logger.LogWarning("identity_mail_failed kind={Kind} recipient_domain={Domain} code={Code}", kind, domain, result.ErrorCode);
return result;
}
catch (Exception ex)
{
logger.LogWarning("identity_mail_failed kind={Kind} code={Code} exception={ExceptionType}", kind, MailSendResult.Unknown, ex.GetType().Name);
return MailSendResult.Fail(MailSendResult.Unknown);
}
}
/// <summary>Public site address + the admin base path + the app path (the admin is mounted under /admin).</summary>
public static string BuildLink(string publicBaseUrl, string appPath) =>
publicBaseUrl.TrimEnd('/') + "/admin" + (appPath.StartsWith('/') ? appPath : "/" + appPath);
private static string? ResolveLogo(string baseUrl, string? logoUrl)
{
if (string.IsNullOrWhiteSpace(logoUrl)) return null;
return logoUrl.StartsWith('/') ? baseUrl + logoUrl : logoUrl;
}
}