Contact: ontvangstadres uit de site-instellingen (instelling > env), PUT /contact-settings/recipient en Berichten-veld (CMS-U11)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:54:03 +01:00
co-authored by Claude Sonnet 5.5
parent 9ff5c8bd94
commit 62f4d4dfe0
29 changed files with 1165 additions and 24 deletions
@@ -156,6 +156,35 @@ public class ContactSettingsController(IContactSettingsService service, IOptions
return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken));
}
[HttpPut("recipient")]
[Consumes("application/json")]
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
public async Task<IActionResult> PutRecipient([FromBody] UpdateContactRecipientRequest? request, CancellationToken cancellationToken)
{
if (!ModelState.IsValid || request is null)
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
}
// null or blank clears the setting (back to the server configuration); anything else must be a plain address.
var address = string.IsNullOrWhiteSpace(request.RecipientEmail) ? null : request.RecipientEmail.Trim();
if (!string.IsNullOrEmpty(address))
{
if (address.Length > 254)
{
return ContactProblems.Validation(new Dictionary<string, string[]> { ["recipientEmail"] = ["tooLong"] }, options.Value.ProblemTypeBase);
}
if (!SlpModularCms.Core.Email.EmailAddressRules.IsValidAddress(address))
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
}
}
return Ok(await service.SetRecipientAsync(address, CallerId(), cancellationToken));
}
private Guid CallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
@@ -42,6 +42,7 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Enabled).IsRequired();
entity.Property(e => e.RecipientEmail).HasMaxLength(254);
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.UpdatedByUserId).IsRequired();
});
@@ -68,6 +68,10 @@ public class ContactSettings
public int Id { get; set; } = SingletonId;
public bool Enabled { get; set; }
/// <summary>The address contact mails are sent to, chosen by an administrator. Null = use Contact:RecipientEmail from the environment.</summary>
public string? RecipientEmail { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public Guid UpdatedByUserId { get; set; }
}
@@ -0,0 +1,139 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
[Migration("20261110224342_ContactSettingsRecipient")]
partial class ContactSettingsRecipient
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<int>("MailAttempts")
.HasColumnType("int");
b.Property<string>("MailError")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("MailStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset?>("NextMailAttemptAt")
.IsConcurrencyToken()
.HasColumnType("datetime");
b.Property<DateTimeOffset>("ReceivedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("RetentionUntil")
.HasColumnType("datetime");
b.Property<string>("SiteId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("RetentionUntil");
b.HasIndex("SiteId", "Status", "ReceivedAt");
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<string>("RecipientEmail")
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<Guid>("UpdatedByUserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.ToTable("ContactSettings", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<Guid>("Key")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.HasKey("SiteId", "Key");
b.HasIndex("CreatedAt");
b.ToTable("ContactIdempotency", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
/// <inheritdoc />
public partial class ContactSettingsRecipient : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "RecipientEmail",
table: "ContactSettings",
type: "varchar(254)",
maxLength: 254,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RecipientEmail",
table: "ContactSettings");
}
}
}
@@ -94,6 +94,10 @@ namespace SlpModularCms.Modules.Contact.Migrations
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<string>("RecipientEmail")
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
@@ -47,7 +47,22 @@ public record UpdateContactMessageStatusRequest(string? Status);
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed, string? MailError = null);
[ExcludeFromCodeCoverage]
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
public record ContactSettingsDto(
bool Enabled,
bool HostEnabled,
string? RecipientEmail = null,
string RecipientSource = ContactRecipientSource.None);
/// <summary>Where the address contact mails go to comes from. The address from the environment is never returned.</summary>
public static class ContactRecipientSource
{
public const string Setting = "setting";
public const string Config = "config";
public const string None = "none";
}
/// <summary>Body of PUT /contact-settings/recipient. null or empty clears the setting (back to the server configuration).</summary>
public record UpdateContactRecipientRequest(string? RecipientEmail);
/// <summary>Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled.</summary>
public record UpdateContactSettingsRequest(bool? Enabled);
@@ -18,25 +18,27 @@ public sealed class ContactMailSender(
IMailTemplateRenderer renderer,
ILanguageResolver languages,
ISiteSettingsService siteSettings,
IContactSettingsService contactSettings,
IMailAvailability availability,
IOptions<EmailOptions> email,
IOptions<AppMailOptions> app,
IOptions<ContactOptions> contact,
ILogger<ContactMailSender> logger) : IContactMailSender
{
public string? NotReadyReason()
public async Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken)
{
if (!availability.IsEnabled)
{
return ContactMailResult.Disabled;
}
return EmailAddressRules.IsValidAddress(contact.Value.RecipientEmail) ? null : ContactMailResult.RecipientNotConfigured;
var (address, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
return address is null ? ContactMailResult.RecipientNotConfigured : null;
}
public async Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken)
{
var notReady = NotReadyReason();
var notReady = await NotReadyReasonAsync(cancellationToken);
if (notReady is not null)
{
return new ContactMailResult(ContactMailOutcome.Skipped, notReady);
@@ -44,6 +46,8 @@ public sealed class ContactMailSender(
try
{
// Read per send: the administrator's setting wins over the environment and changes without a restart.
var (recipient, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(cancellationToken);
var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/');
var language = languages.Resolve(null);
@@ -65,7 +69,7 @@ public sealed class ContactMailSender(
var rendered = renderer.Render(MailKind.ContactMessage, language, model);
var result = await sender.SendAsync(
new OutgoingMail(
contact.Value.RecipientEmail!.Trim(), rendered.Subject, rendered.Html, rendered.Text,
recipient!, rendered.Subject, rendered.Html, rendered.Text,
fromAddress, fromName,
ReplyToAddress: message.Email,
ReplyToName: EmailAddressRules.IsValidDisplayName(message.Name) ? message.Name : null),
@@ -66,7 +66,7 @@ public class ContactMailService(
}
// Mail cannot be sent at all: say why on the messages, count nothing, retry nothing in a loop.
var notReady = sender.NotReadyReason();
var notReady = await sender.NotReadyReasonAsync(cancellationToken);
if (!string.IsNullOrEmpty(notReady))
{
foreach (var message in due.Where(m => m.MailError != notReady))
@@ -47,7 +47,7 @@ public readonly record struct ContactMailResult(ContactMailOutcome Outcome, stri
public interface IContactMailSender
{
/// <summary>Null (or empty) when mail can be sent now, otherwise the short reason code.</summary>
string? NotReadyReason();
Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken);
Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken);
}
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
@@ -53,13 +54,23 @@ public interface IContactSettingsService
Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken);
Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken);
/// <summary>
/// The address contact mails go to: the administrator's setting if filled in and valid, otherwise
/// Contact:RecipientEmail from the configuration, otherwise none. Read from the database on every call.
/// </summary>
Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken);
/// <summary>null or empty clears the setting. The caller has validated the address.</summary>
Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken);
}
public sealed class ContactSettingsService(
IContactRepository repository,
ContactSettingsCache cache,
IOptions<ContactOptions> options,
TimeProvider time) : IContactSettingsService
TimeProvider time,
IContactMailSignal mailSignal) : IContactSettingsService
{
public async Task<bool> IsEnabledAsync(CancellationToken cancellationToken)
{
@@ -76,8 +87,56 @@ public sealed class ContactSettingsService(
public async Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// The administrator's own view is never served from the cache.
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
return new ContactSettingsDto(enabled, options.Value.Enabled);
var settings = await repository.GetSettingsAsync(cancellationToken);
return ToDto(settings);
}
public async Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken)
{
var settings = await repository.GetSettingsAsync(cancellationToken);
return Resolve(settings);
}
private (string? Address, string Source) Resolve(ContactSettings? settings)
{
var fromSetting = settings?.RecipientEmail?.Trim();
if (EmailAddressRules.IsValidAddress(fromSetting))
{
return (fromSetting, ContactRecipientSource.Setting);
}
var fromConfig = options.Value.RecipientEmail?.Trim();
return EmailAddressRules.IsValidAddress(fromConfig)
? (fromConfig, ContactRecipientSource.Config)
: (null, ContactRecipientSource.None);
}
// The administrator sees their own setting, and only where the address comes from (never the environment's address).
private ContactSettingsDto ToDto(ContactSettings? settings)
{
var (_, source) = Resolve(settings);
return new ContactSettingsDto(
settings?.Enabled ?? false, options.Value.Enabled,
string.IsNullOrWhiteSpace(settings?.RecipientEmail) ? null : settings.RecipientEmail, source);
}
public async Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken)
{
var settings = await repository.GetSettingsAsync(cancellationToken);
if (settings is null)
{
settings = new ContactSettings();
repository.Add(settings);
}
settings.RecipientEmail = string.IsNullOrWhiteSpace(recipientEmail) ? null : recipientEmail.Trim();
settings.UpdatedAt = time.GetUtcNow();
settings.UpdatedByUserId = userId;
await repository.SaveChangesAsync(cancellationToken);
// Messages that waited for an address go out at once.
mailSignal.Notify();
return ToDto(settings);
}
public async Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken)
@@ -95,7 +154,7 @@ public sealed class ContactSettingsService(
await repository.SaveChangesAsync(cancellationToken);
cache.Invalidate();
return new ContactSettingsDto(enabled, options.Value.Enabled);
return ToDto(settings);
}
}