U1 mail-foundation (backend): verzender, opties, sjabloon, SiteSettings met toegestane afzenderlijst
IEmailSender met MailKit-implementatie (StartTls, timeout, fouten als waarde), opties met startvalidatie, nl/en sjabloon, taalkeuze, tabel SiteSettings (additieve migratie), SiteSettings-API (Beheerder leest, Eigenaar wijzigt) en emailEnabled/defaultLanguage in de capabilities. Zonder SMTP-host verandert er niets. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -23,6 +23,7 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
|
||||
|
||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||
public DbSet<Invitation> Invitations => Set<Invitation>();
|
||||
public DbSet<SlpModularCms.Core.SiteSettings.SiteSettingsEntity> SiteSettings => Set<SlpModularCms.Core.SiteSettings.SiteSettingsEntity>();
|
||||
public DbSet<ModulePermission> ModulePermissions => Set<ModulePermission>();
|
||||
public DbSet<GlobalAvailabilityState> AvailabilityStates => Set<GlobalAvailabilityState>();
|
||||
|
||||
@@ -75,6 +76,17 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
|
||||
entity.Property(e => e.Email).IsRequired().HasMaxLength(256);
|
||||
});
|
||||
|
||||
// Configuratie voor SiteSettings (een rij, Id = 1)
|
||||
builder.Entity<SlpModularCms.Core.SiteSettings.SiteSettingsEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("SiteSettings");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Id).ValueGeneratedNever();
|
||||
entity.Property(e => e.MailFromAddress).HasMaxLength(256);
|
||||
entity.Property(e => e.MailFromName).HasMaxLength(80);
|
||||
entity.Property(e => e.UpdatedBy).HasMaxLength(256);
|
||||
});
|
||||
|
||||
// Configuratie voor ModulePermissions
|
||||
builder.Entity<ModulePermission>(entity =>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Validation of the values that end up in mail headers. Strict on purpose (allowlist, no control
|
||||
/// characters): a sender address or display name is a header, and a header is an injection target.
|
||||
/// </summary>
|
||||
public static partial class EmailAddressRules
|
||||
{
|
||||
public const int MaxAddressLength = 254;
|
||||
public const int MaxDisplayNameLength = 80;
|
||||
|
||||
// Plain ASCII local@domain.tld: deliberately narrower than RFC 5322 (no quoted strings, no comments).
|
||||
[GeneratedRegex(@"^[A-Za-z0-9._%+\-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$")]
|
||||
private static partial Regex AddressRegex();
|
||||
|
||||
[GeneratedRegex(@"^#[0-9A-Fa-f]{6}$")]
|
||||
private static partial Regex ColourRegex();
|
||||
|
||||
public static bool IsValidAddress(string? value) =>
|
||||
!string.IsNullOrEmpty(value) && value.Length <= MaxAddressLength && AddressRegex().IsMatch(value);
|
||||
|
||||
public static bool IsValidDisplayName(string? value) =>
|
||||
!string.IsNullOrWhiteSpace(value) && value.Trim().Length <= MaxDisplayNameLength && !ContainsControlCharacters(value);
|
||||
|
||||
public static bool IsValidColour(string? value) => !string.IsNullOrEmpty(value) && ColourRegex().IsMatch(value);
|
||||
|
||||
/// <summary>True for CR, LF, NUL and any other control character (header injection and friends).</summary>
|
||||
public static bool ContainsControlCharacters(string value) => value.Any(char.IsControl);
|
||||
|
||||
public static bool IsAllowedSender(string? address, string defaultAddress, IEnumerable<string> allowed)
|
||||
{
|
||||
if (!IsValidAddress(address)) return false;
|
||||
if (string.Equals(address, defaultAddress, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return allowed.Any(a => string.Equals(a, address, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Mail configuration (section <c>Email</c>). Mail is enabled when <see cref="SmtpOptions.Host"/> is set;
|
||||
/// without a host every flow behaves as it did before mail existed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Same shape and names as SimpleDeckApp's options on purpose, extended with the settings this CMS
|
||||
/// needs (allowlist of sender addresses, brand, timeout). Credentials come from the environment
|
||||
/// (<c>Email__Smtp__Username</c>, <c>Email__Smtp__Password</c>), never from a committed file.
|
||||
/// </remarks>
|
||||
public sealed class EmailOptions
|
||||
{
|
||||
public const string SectionName = "Email";
|
||||
|
||||
/// <summary>Default sender address when the site settings hold none.</summary>
|
||||
public string FromAddress { get; set; } = "";
|
||||
|
||||
/// <summary>Default sender display name; also used as the site name inside the mail.</summary>
|
||||
public string FromName { get; set; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// Sender addresses a site may choose in its settings. Mandatory: a free address could send as a
|
||||
/// domain the SMTP account is not authorised for (SPF/DKIM mismatch, spoofing). Empty means only
|
||||
/// <see cref="FromAddress"/> is allowed.
|
||||
/// </summary>
|
||||
public string[] AllowedFromAddresses { get; set; } = [];
|
||||
|
||||
/// <summary>Optional logo for the mail header, absolute or relative to <c>App:PublicBaseUrl</c>.</summary>
|
||||
public string LogoUrl { get; set; } = "";
|
||||
|
||||
/// <summary>Optional brand colour, <c>#rrggbb</c>.</summary>
|
||||
public string BrandColor { get; set; } = "";
|
||||
|
||||
public SmtpOptions Smtp { get; set; } = new();
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public override string ToString() => $"Email(From={FromAddress}, Host={Smtp.Host})"; // never the credentials
|
||||
}
|
||||
|
||||
public sealed class SmtpOptions
|
||||
{
|
||||
public string Host { get; set; } = "";
|
||||
public int Port { get; set; } = 587;
|
||||
public bool EnableSsl { get; set; } = true;
|
||||
public string Username { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
|
||||
/// <summary>Connect and send are bounded by this, because mail is sent inside the request.</summary>
|
||||
public int TimeoutSeconds { get; set; } = 10;
|
||||
}
|
||||
|
||||
/// <summary>Site-level settings around mail (section <c>App</c>).</summary>
|
||||
public sealed class AppMailOptions
|
||||
{
|
||||
public const string SectionName = "App";
|
||||
|
||||
/// <summary>Public https address of the site, used to build links in mails (for example https://test.andreaslop.nl).</summary>
|
||||
public string PublicBaseUrl { get; set; } = "";
|
||||
|
||||
/// <summary>Default language of the site for mails: nl or en.</summary>
|
||||
public string DefaultLanguage { get; set; } = "nl";
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Start-up validation of the mail configuration. Only runs checks when mail is enabled (an SMTP host
|
||||
/// is set); a host without mail configuration starts exactly as before. Messages never contain the
|
||||
/// credentials.
|
||||
/// </summary>
|
||||
public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValidateOptions<EmailOptions>
|
||||
{
|
||||
public ValidateOptionsResult Validate(string? name, EmailOptions options)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(options.Smtp.Host))
|
||||
return ValidateOptionsResult.Success; // mail disabled
|
||||
|
||||
var failures = new List<string>();
|
||||
|
||||
if (!EmailAddressRules.IsValidAddress(options.FromAddress))
|
||||
failures.Add("Email:FromAddress must be a valid e-mail address.");
|
||||
if (!EmailAddressRules.IsValidDisplayName(options.FromName))
|
||||
failures.Add($"Email:FromName is required (1..{EmailAddressRules.MaxDisplayNameLength} characters, no control characters).");
|
||||
if (options.Smtp.Port is < 1 or > 65535)
|
||||
failures.Add("Email:Smtp:Port must be between 1 and 65535.");
|
||||
if (options.Smtp.TimeoutSeconds is < 1 or > 60)
|
||||
failures.Add("Email:Smtp:TimeoutSeconds must be between 1 and 60.");
|
||||
if (!string.IsNullOrEmpty(options.Smtp.Username) && string.IsNullOrEmpty(options.Smtp.Password))
|
||||
failures.Add("Email:Smtp:Password is required when Email:Smtp:Username is set.");
|
||||
if (!string.IsNullOrEmpty(options.BrandColor) && !EmailAddressRules.IsValidColour(options.BrandColor))
|
||||
failures.Add("Email:BrandColor must look like #rrggbb.");
|
||||
foreach (var allowed in options.AllowedFromAddresses)
|
||||
{
|
||||
if (!EmailAddressRules.IsValidAddress(allowed))
|
||||
failures.Add("Email:AllowedFromAddresses contains an invalid e-mail address.");
|
||||
}
|
||||
|
||||
var baseUrl = app.Value.PublicBaseUrl;
|
||||
if (!IsValidPublicBaseUrl(baseUrl))
|
||||
failures.Add("App:PublicBaseUrl must be an absolute https URL (http only for localhost) without a path.");
|
||||
if (!MailLanguages.IsSupported(app.Value.DefaultLanguage))
|
||||
failures.Add("App:DefaultLanguage must be 'nl' or 'en'.");
|
||||
|
||||
if (!string.IsNullOrEmpty(options.LogoUrl) && !IsValidLogoUrl(options.LogoUrl))
|
||||
failures.Add("Email:LogoUrl must be an https URL or a path starting with '/'.");
|
||||
|
||||
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
|
||||
}
|
||||
|
||||
public static bool IsValidPublicBaseUrl(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value) || !Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
|
||||
var local = uri.IsLoopback;
|
||||
if (uri.Scheme != Uri.UriSchemeHttps && !(local && uri.Scheme == Uri.UriSchemeHttp)) return false;
|
||||
return (uri.AbsolutePath == "/" || uri.AbsolutePath == "") && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment)
|
||||
&& string.IsNullOrEmpty(uri.UserInfo);
|
||||
}
|
||||
|
||||
private static bool IsValidLogoUrl(string value)
|
||||
{
|
||||
if (value.StartsWith('/') && !value.StartsWith("//") && !value.Any(char.IsControl)) return true;
|
||||
return Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
public static class EmailServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the mail building blocks. Mail is on when <c>Email:Smtp:Host</c> is set; otherwise a
|
||||
/// <see cref="NullEmailSender"/> is registered and every flow behaves as before mail existed.
|
||||
/// The options are validated at start-up (only when mail is on).
|
||||
/// </summary>
|
||||
public static IServiceCollection AddCmsEmail(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<AppMailOptions>().Bind(configuration.GetSection(AppMailOptions.SectionName));
|
||||
services.AddOptions<EmailOptions>().Bind(configuration.GetSection(EmailOptions.SectionName)).ValidateOnStart();
|
||||
services.AddSingleton<IValidateOptions<EmailOptions>, EmailOptionsValidator>();
|
||||
|
||||
var enabled = !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
|
||||
if (enabled)
|
||||
services.TryAddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
else
|
||||
services.TryAddSingleton<IEmailSender, NullEmailSender>();
|
||||
|
||||
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
|
||||
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
|
||||
services.TryAddScoped<ISiteSettingsService, SiteSettingsService>();
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>True when an SMTP host is configured.</summary>
|
||||
public static bool IsEmailEnabled(this IConfiguration configuration) =>
|
||||
!string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Sends one mail. Same name and first four parameters as SimpleDeckApp's <c>IEmailSender.SendAsync</c>
|
||||
/// (see the extension below); differs on purpose in that it returns a <see cref="MailSendResult"/>
|
||||
/// instead of throwing, because in this CMS a mail failure must never fail the action that triggered it.
|
||||
/// </summary>
|
||||
public interface IEmailSender
|
||||
{
|
||||
Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public static class EmailSenderExtensions
|
||||
{
|
||||
/// <summary>SimpleDeckApp-shaped call: to, subject, html body.</summary>
|
||||
public static Task<MailSendResult> SendAsync(
|
||||
this IEmailSender sender, string toAddress, string subject, string htmlBody, CancellationToken cancellationToken = default) =>
|
||||
sender.SendAsync(new OutgoingMail(toAddress, subject, htmlBody), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Registered when no SMTP host is configured: reports "disabled" so callers never null-check.</summary>
|
||||
public sealed class NullEmailSender : IEmailSender
|
||||
{
|
||||
public Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(MailSendResult.Fail(MailSendResult.Disabled));
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
public interface IMailTemplateRenderer
|
||||
{
|
||||
RenderedMail Render(MailKind kind, string language, MailModel model);
|
||||
}
|
||||
|
||||
public interface ILanguageResolver
|
||||
{
|
||||
/// <summary>The user's language if supported, else the site default, else Dutch.</summary>
|
||||
string Resolve(string? preferredLanguage);
|
||||
}
|
||||
|
||||
public sealed class LanguageResolver(IOptions<AppMailOptions> options) : ILanguageResolver
|
||||
{
|
||||
public string Resolve(string? preferredLanguage) =>
|
||||
MailLanguages.Normalize(preferredLanguage)
|
||||
?? MailLanguages.Normalize(options.Value.DefaultLanguage)
|
||||
?? MailLanguages.Dutch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One shared layout, texts per language kept in code. Every dynamic value is HTML-encoded for the
|
||||
/// HTML part; the subject and plain-text part carry the raw values (no markup there). A missing
|
||||
/// language or key falls back to Dutch. Table layout and inline CSS only, so it renders in mail clients.
|
||||
/// </summary>
|
||||
public sealed class MailTemplateRenderer : IMailTemplateRenderer
|
||||
{
|
||||
private const string DefaultColour = "#1f2937";
|
||||
|
||||
private sealed record Texts(
|
||||
string Subject, string Heading, string Intro, string? Button, string? Note, string Footer);
|
||||
|
||||
// {0} = site name, {1} = role, {2} = minutes/hours text. Keys: kind, then language.
|
||||
private static readonly Dictionary<MailKind, Dictionary<string, Texts>> Catalog = new()
|
||||
{
|
||||
[MailKind.Invitation] = new()
|
||||
{
|
||||
["nl"] = new("Uitnodiging voor {0}", "Je bent uitgenodigd",
|
||||
"Je bent uitgenodigd om een account aan te maken voor {0}. Kies met de knop hieronder je wachtwoord om je account te activeren.",
|
||||
"Account activeren", "Deze link is {2} geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging.",
|
||||
"Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("Invitation to {0}", "You have been invited",
|
||||
"You have been invited to create an account for {0}. Use the button below to choose your password and activate your account.",
|
||||
"Activate account", "This link is valid for {2}. If it has expired, ask the administrator for a new invitation.",
|
||||
"This message was sent automatically by {0}.")
|
||||
},
|
||||
[MailKind.NewInvitationLink] = new()
|
||||
{
|
||||
["nl"] = new("Nieuwe uitnodigingslink voor {0}", "Je hebt een nieuwe uitnodigingslink",
|
||||
"Er is een nieuwe uitnodigingslink voor je aangemaakt voor {0}. De vorige link werkt niet meer.",
|
||||
"Account activeren", "Deze link is {2} geldig.",
|
||||
"Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("New invitation link for {0}", "You have a new invitation link",
|
||||
"A new invitation link has been created for you for {0}. The previous link no longer works.",
|
||||
"Activate account", "This link is valid for {2}.",
|
||||
"This message was sent automatically by {0}.")
|
||||
},
|
||||
[MailKind.PasswordReset] = new()
|
||||
{
|
||||
["nl"] = new("Wachtwoord opnieuw instellen voor {0}", "Wachtwoord opnieuw instellen",
|
||||
"Er is gevraagd om het wachtwoord van je account bij {0} opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen.",
|
||||
"Nieuw wachtwoord kiezen", "Deze link is {2} geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd.",
|
||||
"Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("Reset your password for {0}", "Reset your password",
|
||||
"A request was made to reset the password of your account at {0}. Use the button below to choose a new password.",
|
||||
"Choose a new password", "This link is valid for {2} and works once. Did you not ask for this? Ignore this message: your password stays unchanged.",
|
||||
"This message was sent automatically by {0}.")
|
||||
},
|
||||
[MailKind.AccountDeactivated] = new()
|
||||
{
|
||||
["nl"] = new("Je account bij {0} is gedeactiveerd", "Account gedeactiveerd",
|
||||
"Een beheerder heeft je account bij {0} gedeactiveerd. Je kunt niet meer inloggen.",
|
||||
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
|
||||
"Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("Your account at {0} has been deactivated", "Account deactivated",
|
||||
"An administrator has deactivated your account at {0}. You can no longer sign in.",
|
||||
null, "Think this is a mistake? Please contact the administrator.",
|
||||
"This message was sent automatically by {0}.")
|
||||
},
|
||||
[MailKind.AccountReactivated] = new()
|
||||
{
|
||||
["nl"] = new("Je account bij {0} is weer actief", "Account weer actief",
|
||||
"Een beheerder heeft je account bij {0} weer geactiveerd. Je kunt weer inloggen.",
|
||||
"Inloggen", null, "Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("Your account at {0} is active again", "Account active again",
|
||||
"An administrator has reactivated your account at {0}. You can sign in again.",
|
||||
"Sign in", null, "This message was sent automatically by {0}.")
|
||||
},
|
||||
[MailKind.RoleChanged] = new()
|
||||
{
|
||||
["nl"] = new("Je rol bij {0} is gewijzigd", "Rol gewijzigd",
|
||||
"Een beheerder heeft je rol bij {0} gewijzigd naar: {1}.",
|
||||
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
|
||||
"Deze mail is automatisch verstuurd door {0}."),
|
||||
["en"] = new("Your role at {0} has changed", "Role changed",
|
||||
"An administrator has changed your role at {0} to: {1}.",
|
||||
null, "Think this is a mistake? Please contact the administrator.",
|
||||
"This message was sent automatically by {0}.")
|
||||
}
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, Dictionary<string, string>> Roles = new()
|
||||
{
|
||||
["nl"] = new() { ["Owner"] = "Eigenaar", ["Administrator"] = "Beheerder", ["User"] = "Gebruiker" },
|
||||
["en"] = new() { ["Owner"] = "Owner", ["Administrator"] = "Administrator", ["User"] = "User" }
|
||||
};
|
||||
|
||||
public RenderedMail Render(MailKind kind, string language, MailModel model)
|
||||
{
|
||||
var lang = MailLanguages.Normalize(language) ?? MailLanguages.Dutch;
|
||||
var perKind = Catalog[kind];
|
||||
var t = perKind.TryGetValue(lang, out var found) ? found : perKind[MailLanguages.Dutch];
|
||||
|
||||
var site = Plain(model.SiteName);
|
||||
var role = RoleName(lang, model.Detail);
|
||||
var validity = Validity(lang, model.ValidForMinutes);
|
||||
|
||||
string F(string template) => string.Format(template, site, role, validity);
|
||||
|
||||
var subject = Plain(F(t.Subject));
|
||||
var heading = F(t.Heading);
|
||||
var intro = F(t.Intro);
|
||||
var note = t.Note is null ? null : F(t.Note);
|
||||
var footer = F(t.Footer);
|
||||
var greeting = string.IsNullOrWhiteSpace(model.RecipientName)
|
||||
? null
|
||||
: (lang == "en" ? $"Hello {model.RecipientName.Trim()}," : $"Hallo {model.RecipientName.Trim()},");
|
||||
|
||||
var colour = EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour;
|
||||
var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl);
|
||||
|
||||
return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer),
|
||||
BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer));
|
||||
}
|
||||
|
||||
private static string RoleName(string lang, string? key) =>
|
||||
key is not null && Roles[lang].TryGetValue(key, out var name) ? name : (key ?? "");
|
||||
|
||||
private static string Validity(string lang, int? minutes)
|
||||
{
|
||||
if (minutes is null) return "";
|
||||
var m = minutes.Value;
|
||||
if (m % 60 == 0)
|
||||
{
|
||||
var h = m / 60;
|
||||
return lang == "en" ? $"{h} hour{(h == 1 ? "" : "s")}" : $"{h} uur";
|
||||
}
|
||||
return lang == "en" ? $"{m} minutes" : $"{m} minuten";
|
||||
}
|
||||
|
||||
/// <summary>For the subject and text: no markup, and no line breaks (a subject is a header).</summary>
|
||||
private static string Plain(string value) => new(value.Where(c => !char.IsControl(c)).ToArray());
|
||||
|
||||
private static string E(string value) => WebUtility.HtmlEncode(value);
|
||||
|
||||
private static string BuildHtml(
|
||||
MailModel model, string site, string colour, string? greeting, string heading, string intro,
|
||||
string? button, string? note, string footer)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<!DOCTYPE html><html><body style=\"margin:0;padding:0;background:#f3f4f6;\">");
|
||||
sb.Append("<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\"><tr><td align=\"center\">");
|
||||
sb.Append("<table role=\"presentation\" width=\"560\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:560px;width:100%;background:#ffffff;border-radius:8px;font-family:Arial,Helvetica,sans-serif;color:#111827;\">");
|
||||
sb.Append($"<tr><td style=\"padding:24px 32px;border-bottom:3px solid {colour};\">");
|
||||
if (!string.IsNullOrEmpty(model.LogoUrl))
|
||||
sb.Append($"<img src=\"{E(model.LogoUrl)}\" alt=\"{E(site)}\" height=\"48\" style=\"display:block;height:48px;width:auto;border:0;\">");
|
||||
else
|
||||
sb.Append($"<span style=\"font-size:20px;font-weight:bold;color:{colour};\">{E(site)}</span>");
|
||||
sb.Append("</td></tr><tr><td style=\"padding:32px;font-size:15px;line-height:1.5;\">");
|
||||
sb.Append($"<h1 style=\"margin:0 0 16px 0;font-size:22px;color:{colour};\">{E(heading)}</h1>");
|
||||
if (greeting is not null) sb.Append($"<p style=\"margin:0 0 12px 0;\">{E(greeting)}</p>");
|
||||
sb.Append($"<p style=\"margin:0 0 24px 0;\">{E(intro)}</p>");
|
||||
if (button is not null && !string.IsNullOrEmpty(model.ActionUrl))
|
||||
{
|
||||
sb.Append($"<p style=\"margin:0 0 24px 0;\"><a href=\"{E(model.ActionUrl)}\" style=\"display:inline-block;background:{colour};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:bold;\">{E(button)}</a></p>");
|
||||
sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;word-break:break-all;\">{E(model.ActionUrl)}</p>");
|
||||
}
|
||||
if (note is not null) sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;\">{E(note)}</p>");
|
||||
sb.Append("</td></tr>");
|
||||
sb.Append($"<tr><td style=\"padding:16px 32px;font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;\">{E(footer)}</td></tr>");
|
||||
sb.Append("</table></td></tr></table></body></html>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string BuildText(string? greeting, string heading, string intro, string? url, string? note, string footer)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine(heading).AppendLine();
|
||||
if (greeting is not null) sb.AppendLine(greeting).AppendLine();
|
||||
sb.AppendLine(intro).AppendLine();
|
||||
if (url is not null) sb.AppendLine(url).AppendLine();
|
||||
if (note is not null) sb.AppendLine(note).AppendLine();
|
||||
sb.AppendLine("--").AppendLine(footer);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>Outcome of one send. Sending never throws into the caller: a failure is a value.</summary>
|
||||
public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
|
||||
{
|
||||
public const string Disabled = "disabled";
|
||||
public const string NotConfigured = "not_configured";
|
||||
public const string Timeout = "timeout";
|
||||
public const string AuthFailed = "auth_failed";
|
||||
public const string Rejected = "rejected";
|
||||
public const string Unknown = "unknown";
|
||||
|
||||
public static MailSendResult Ok { get; } = new(true, null);
|
||||
public static MailSendResult Fail(string code) => new(false, code);
|
||||
}
|
||||
|
||||
/// <summary>One message to send. <see cref="FromAddress"/>/<see cref="FromName"/> null means the configured defaults.</summary>
|
||||
public sealed record OutgoingMail(
|
||||
string ToAddress,
|
||||
string Subject,
|
||||
string HtmlBody,
|
||||
string? TextBody = null,
|
||||
string? FromAddress = null,
|
||||
string? FromName = null);
|
||||
|
||||
public enum MailKind
|
||||
{
|
||||
Invitation,
|
||||
NewInvitationLink,
|
||||
PasswordReset,
|
||||
AccountDeactivated,
|
||||
AccountReactivated,
|
||||
RoleChanged
|
||||
}
|
||||
|
||||
/// <summary>Values the template needs. <see cref="Detail"/> carries the role key for <see cref="MailKind.RoleChanged"/>.</summary>
|
||||
public sealed record MailModel(
|
||||
string SiteName,
|
||||
string? RecipientName = null,
|
||||
string? ActionUrl = null,
|
||||
int? ValidForMinutes = null,
|
||||
string? Detail = null,
|
||||
string? LogoUrl = null,
|
||||
string? BrandColor = null);
|
||||
|
||||
public sealed record RenderedMail(string Subject, string Html, string Text);
|
||||
|
||||
public static class MailLanguages
|
||||
{
|
||||
public const string Dutch = "nl";
|
||||
public const string English = "en";
|
||||
|
||||
public static bool IsSupported(string? value) => Normalize(value) is not null;
|
||||
|
||||
/// <summary>Returns "nl" or "en" for a supported value (case-insensitive, region tags allowed), otherwise null.</summary>
|
||||
public static string? Normalize(string? value)
|
||||
{
|
||||
var v = value?.Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrEmpty(v)) return null;
|
||||
var primary = v.Split('-', '_')[0];
|
||||
return primary is Dutch or English ? primary : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using MailKit;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// MailKit/MimeKit sender, following SimpleDeckApp: StartTls when <c>EnableSsl</c>, authenticate only
|
||||
/// when a username is configured. Every failure is caught here and mapped to a short error code; the
|
||||
/// exception text is never logged or returned because it can quote addresses.
|
||||
/// </summary>
|
||||
public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
|
||||
{
|
||||
private readonly EmailOptions _options = options.Value;
|
||||
|
||||
public async Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_options.Smtp.Host))
|
||||
return MailSendResult.Fail(MailSendResult.NotConfigured);
|
||||
|
||||
var fromAddress = mail.FromAddress ?? _options.FromAddress;
|
||||
var fromName = mail.FromName ?? _options.FromName;
|
||||
|
||||
// Everything that becomes a header is checked first: a bad value is refused, never sent.
|
||||
if (!EmailAddressRules.IsValidAddress(mail.ToAddress)
|
||||
|| !EmailAddressRules.IsValidAddress(fromAddress)
|
||||
|| EmailAddressRules.ContainsControlCharacters(mail.Subject)
|
||||
|| EmailAddressRules.ContainsControlCharacters(fromName))
|
||||
{
|
||||
logger.LogWarning("identity_mail_failed code={Code} reason=invalid_header", MailSendResult.Rejected);
|
||||
return MailSendResult.Fail(MailSendResult.Rejected);
|
||||
}
|
||||
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress(fromName, fromAddress));
|
||||
message.To.Add(MailboxAddress.Parse(mail.ToAddress));
|
||||
message.Subject = mail.Subject;
|
||||
message.Body = new BodyBuilder { HtmlBody = mail.HtmlBody, TextBody = mail.TextBody }.ToMessageBody();
|
||||
|
||||
var timeout = TimeSpan.FromSeconds(_options.Smtp.TimeoutSeconds);
|
||||
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutSource.CancelAfter(timeout);
|
||||
|
||||
try
|
||||
{
|
||||
using var client = new SmtpClient { Timeout = (int)timeout.TotalMilliseconds };
|
||||
await client.ConnectAsync(
|
||||
_options.Smtp.Host,
|
||||
_options.Smtp.Port,
|
||||
_options.Smtp.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None,
|
||||
timeoutSource.Token);
|
||||
|
||||
if (!string.IsNullOrEmpty(_options.Smtp.Username))
|
||||
await client.AuthenticateAsync(_options.Smtp.Username, _options.Smtp.Password, timeoutSource.Token);
|
||||
|
||||
await client.SendAsync(message, timeoutSource.Token);
|
||||
await client.DisconnectAsync(true, timeoutSource.Token);
|
||||
return MailSendResult.Ok;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var code = Map(ex, cancellationToken);
|
||||
// The exception TYPE only: its message may contain the recipient or server replies.
|
||||
logger.LogWarning("identity_mail_failed code={Code} exception={ExceptionType}", code, ex.GetType().Name);
|
||||
return MailSendResult.Fail(code);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Map(Exception ex, CancellationToken callerToken) => ex switch
|
||||
{
|
||||
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
|
||||
TimeoutException => MailSendResult.Timeout,
|
||||
OperationCanceledException => MailSendResult.Unknown,
|
||||
AuthenticationException => MailSendResult.AuthFailed,
|
||||
SmtpCommandException or SmtpProtocolException or SslHandshakeException => MailSendResult.Rejected,
|
||||
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
|
||||
_ => MailSendResult.Unknown
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Core.Exceptions;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
@@ -66,6 +67,8 @@ public static class ServiceCollectionExtensions
|
||||
$"{InvitationSettings.SectionName}:ExpiryHours must be between 1 and {InvitationSettings.MaxExpiryHours}.")
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddCmsEmail(configuration);
|
||||
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddScoped<IInvitationService, InvitationService>();
|
||||
services.AddScoped<ISetupService, SetupService>();
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Email;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting;
|
||||
|
||||
@@ -12,15 +14,26 @@ namespace SlpModularCms.Core.Hosting;
|
||||
public class SystemController : ControllerBase
|
||||
{
|
||||
private readonly ModuleOrchestrator _orchestrator;
|
||||
private readonly IOptions<EmailOptions> _email;
|
||||
private readonly IOptions<AppMailOptions> _app;
|
||||
|
||||
public SystemController(ModuleOrchestrator orchestrator)
|
||||
public SystemController(ModuleOrchestrator orchestrator, IOptions<EmailOptions> email, IOptions<AppMailOptions> app)
|
||||
{
|
||||
_orchestrator = orchestrator;
|
||||
_email = email;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
[HttpGet("capabilities")]
|
||||
public IActionResult GetCapabilities()
|
||||
{
|
||||
return Ok(new { Modules = _orchestrator.ModuleNames });
|
||||
// EmailEnabled tells the UI whether mail actions exist on this site; DefaultLanguage is the
|
||||
// site's mail language fallback. Neither exposes configuration values beyond that.
|
||||
return Ok(new
|
||||
{
|
||||
Modules = _orchestrator.ModuleNames,
|
||||
EmailEnabled = !string.IsNullOrWhiteSpace(_email.Value.Smtp.Host),
|
||||
DefaultLanguage = MailLanguages.Normalize(_app.Value.DefaultLanguage) ?? MailLanguages.Dutch
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+466
@@ -0,0 +1,466 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Core.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Core.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20261108170420_AddSiteSettings")]
|
||||
partial class AddSiteSettings
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 64);
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("FriendlyName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Xml")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("DataProtectionKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("RoleClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("UserClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("UserLogins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("UserId", "LoginProvider", "Name");
|
||||
|
||||
b.ToTable("UserTokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationRole", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex");
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.GlobalAvailabilityState", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("LastUpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("AvailabilityState", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.Invitation", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiryDate")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsAccepted")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Invitations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("ModuleName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.Property<string>("Permission")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.HasKey("UserId", "ModuleName", "Permission");
|
||||
|
||||
b.ToTable("ModulePermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("CreatedByIp")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiryDate")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsUsed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.SiteSettings.SiteSettingsEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("MailFromAddress")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("MailFromName")
|
||||
.HasMaxLength(80)
|
||||
.HasColumnType("varchar(80)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("SiteSettings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
|
||||
.WithMany("ModulePermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Navigation("ModulePermissions");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Core.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSiteSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SiteSettings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false),
|
||||
MailFromAddress = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
|
||||
MailFromName = table.Column<string>(type: "varchar(80)", maxLength: 80, nullable: true),
|
||||
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
UpdatedBy = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SiteSettings", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "SiteSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -353,6 +353,31 @@ namespace SlpModularCms.Core.Migrations
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.SiteSettings.SiteSettingsEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("MailFromAddress")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("MailFromName")
|
||||
.HasMaxLength(80)
|
||||
.HasColumnType("varchar(80)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("SiteSettings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace SlpModularCms.Core.SiteSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Per-site settings, one row (Id is always 1). Only mail settings for now; the planned brand/site-name
|
||||
/// settings would live here too. A null column means "use the configured default".
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SiteSettingsEntity
|
||||
{
|
||||
public const int SingletonId = 1;
|
||||
|
||||
public int Id { get; set; } = SingletonId;
|
||||
public string? MailFromAddress { get; set; }
|
||||
public string? MailFromName { get; set; }
|
||||
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Email;
|
||||
|
||||
namespace SlpModularCms.Core.SiteSettings;
|
||||
|
||||
public sealed record MailSettingsView(
|
||||
bool EmailEnabled,
|
||||
string FromAddress,
|
||||
string FromName,
|
||||
string DefaultFromAddress,
|
||||
string DefaultFromName,
|
||||
IReadOnlyList<string> AllowedFromAddresses,
|
||||
bool IsCustomized);
|
||||
|
||||
public readonly record struct SetMailResult(bool Ok, string? Error)
|
||||
{
|
||||
public const string MailDisabled = "mail_disabled";
|
||||
public const string InvalidAddress = "invalid_address";
|
||||
public const string AddressNotAllowed = "address_not_allowed";
|
||||
public const string InvalidName = "invalid_name";
|
||||
|
||||
public static SetMailResult Success { get; } = new(true, null);
|
||||
public static SetMailResult Fail(string error) => new(false, error);
|
||||
}
|
||||
|
||||
public interface ISiteSettingsService
|
||||
{
|
||||
Task<MailSettingsView> GetMailAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sets the sender; both values null (or blank) resets to the configured defaults.</summary>
|
||||
Task<SetMailResult> SetMailAsync(string? fromAddress, string? fromName, string? actor, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The sender a mail is sent with right now: stored values if still allowed, else the defaults.</summary>
|
||||
Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class SiteSettingsService(ApplicationDbContext db, IOptions<EmailOptions> options) : ISiteSettingsService
|
||||
{
|
||||
private readonly EmailOptions _options = options.Value;
|
||||
|
||||
private bool Enabled => !string.IsNullOrWhiteSpace(_options.Smtp.Host);
|
||||
|
||||
private IReadOnlyList<string> Allowed() =>
|
||||
new[] { _options.FromAddress }.Concat(_options.AllowedFromAddresses)
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
public async Task<MailSettingsView> GetMailAsync(CancellationToken ct = default)
|
||||
{
|
||||
var (address, name) = await GetEffectiveSenderAsync(ct);
|
||||
var row = await db.SiteSettings.AsNoTracking().FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
|
||||
var customized = row is not null && (row.MailFromAddress is not null || row.MailFromName is not null);
|
||||
return new MailSettingsView(Enabled, address, name, _options.FromAddress, _options.FromName, Allowed(), customized);
|
||||
}
|
||||
|
||||
public async Task<SetMailResult> SetMailAsync(string? fromAddress, string? fromName, string? actor, CancellationToken ct = default)
|
||||
{
|
||||
if (!Enabled) return SetMailResult.Fail(SetMailResult.MailDisabled);
|
||||
|
||||
var reset = string.IsNullOrWhiteSpace(fromAddress) && string.IsNullOrWhiteSpace(fromName);
|
||||
string? address = null;
|
||||
string? name = null;
|
||||
|
||||
if (!reset)
|
||||
{
|
||||
address = fromAddress?.Trim();
|
||||
name = fromName?.Trim();
|
||||
if (!EmailAddressRules.IsValidAddress(address)) return SetMailResult.Fail(SetMailResult.InvalidAddress);
|
||||
if (!EmailAddressRules.IsAllowedSender(address, _options.FromAddress, _options.AllowedFromAddresses))
|
||||
return SetMailResult.Fail(SetMailResult.AddressNotAllowed);
|
||||
if (!EmailAddressRules.IsValidDisplayName(name)) return SetMailResult.Fail(SetMailResult.InvalidName);
|
||||
}
|
||||
|
||||
var row = await db.SiteSettings.FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
|
||||
if (row is null)
|
||||
{
|
||||
row = new SiteSettingsEntity();
|
||||
db.SiteSettings.Add(row);
|
||||
}
|
||||
|
||||
row.MailFromAddress = address;
|
||||
row.MailFromName = name;
|
||||
row.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
row.UpdatedBy = actor;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return SetMailResult.Success;
|
||||
}
|
||||
|
||||
public async Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default)
|
||||
{
|
||||
var row = await db.SiteSettings.AsNoTracking().FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
|
||||
|
||||
// A stored address is re-checked on every use: if the allowlist has since been narrowed, the
|
||||
// mail falls back to the configured default instead of sending as an address no longer allowed.
|
||||
var address = row?.MailFromAddress is { } stored
|
||||
&& EmailAddressRules.IsAllowedSender(stored, _options.FromAddress, _options.AllowedFromAddresses)
|
||||
? stored
|
||||
: _options.FromAddress;
|
||||
var name = row?.MailFromName is { } storedName && EmailAddressRules.IsValidDisplayName(storedName)
|
||||
? storedName
|
||||
: _options.FromName;
|
||||
return (address, name);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Asp.Versioning.Mvc" Version="10.0.0" />
|
||||
<PackageReference Include="MailKit" Version="4.18.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
|
||||
<!--
|
||||
Persists the Data Protection key ring in the database instead of on the filesystem.
|
||||
|
||||
Reference in New Issue
Block a user