Contactbeheer: berichten, schakelaar en tweelaagse poort voor het formulier
Beheerroutes zonder /admin-segment op contact-messages (lijst met spam apart en ongelezen-teller zonder spam, detail, status, verwijderen, opnieuw versturen met eigen limiet) en contact-settings voor de CMS-schakelaar, allemaal AdminOnly. Het formulier is alleen open als de hostvlag EN de CMS-schakelaar (standaard uit) aan staan; de hostvlag wordt eerst gecontroleerd zodat de database niet wordt aangeraakt. Bij uitgeschakelde host antwoorden de beheerroutes 404. OpenAPI-document bijgewerkt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,8 +45,20 @@ public class ContactModule : IModule
|
||||
services.AddSingleton<IContactTokenService, ContactTokenService>();
|
||||
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
|
||||
services.AddScoped<IContactMailSender, NoOpContactMailSender>();
|
||||
services.AddScoped<IContactFormGate, HostFlagContactFormGate>();
|
||||
// Gate: the form is open only if the host switch AND the CMS switch are on. The host switch
|
||||
// is asked first, so with it off the database is never touched.
|
||||
services.AddSingleton<ContactSettingsCache>();
|
||||
services.AddScoped<IContactSettingsService, ContactSettingsService>();
|
||||
services.AddScoped<HostFlagContactFormGate>();
|
||||
services.AddScoped<CmsFlagContactFormGate>();
|
||||
services.AddScoped<IContactFormGate>(sp => new CompositeContactFormGate(
|
||||
[
|
||||
sp.GetRequiredService<HostFlagContactFormGate>(),
|
||||
sp.GetRequiredService<CmsFlagContactFormGate>(),
|
||||
]));
|
||||
services.AddScoped<IContactAdminService, ContactAdminService>();
|
||||
services.AddScoped<ContactRouteFilter>();
|
||||
services.AddScoped<ContactAdminRouteFilter>();
|
||||
services.AddHostedService<ContactRetentionService>();
|
||||
|
||||
// The contact details of the OpenAPI document (named options of document 'v1', so the shared
|
||||
@@ -62,6 +74,8 @@ public class ContactModule : IModule
|
||||
Window(config, "ContactForm", 5, 600, context));
|
||||
limiter.AddPolicy(ContactMessagesController.TokenPolicy, context =>
|
||||
Window(config, "ContactToken", 20, 600, context));
|
||||
limiter.AddPolicy(ContactMessagesAdminController.ResendPolicy, context =>
|
||||
Window(config, "ContactResend", 5, 600, context));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Models;
|
||||
using SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// The management routes need the contact tables, which exist only while the host switch
|
||||
/// (<c>Contact:Enabled</c>) is on. While it is off they answer 404 with an empty body. The CMS
|
||||
/// switch deliberately does NOT close them: otherwise nobody could switch the form back on.
|
||||
/// </summary>
|
||||
public sealed class ContactAdminRouteFilter(IOptions<ContactOptions> options) : IResourceFilter
|
||||
{
|
||||
public void OnResourceExecuting(ResourceExecutingContext context)
|
||||
{
|
||||
if (!options.Value.Enabled)
|
||||
{
|
||||
context.Result = new NotFoundResult();
|
||||
}
|
||||
}
|
||||
|
||||
public void OnResourceExecuted(ResourceExecutedContext context)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Management of the stored messages. Same resource name as the public routes, no admin segment:
|
||||
/// access is decided by authorization alone (AdminOnly). Not an <c>[ApiController]</c>, like the
|
||||
/// public controller, so every 400 is in our own problem shape.
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(IgnoreApi = false)]
|
||||
[Route("contact-messages")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
[ServiceFilter(typeof(ContactAdminRouteFilter))]
|
||||
public class ContactMessagesAdminController(IContactAdminService service, IOptions<ContactOptions> options) : ControllerBase
|
||||
{
|
||||
public const string ResendPolicy = "contact-resend";
|
||||
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(ContactMessageList), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] string? status, [FromQuery] int page = 1, [FromQuery] int pageSize = ContactAdminService.DefaultPageSize,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var invalid = new List<string>();
|
||||
foreach (var (key, entry) in ModelState)
|
||||
{
|
||||
if (entry.Errors.Count > 0)
|
||||
{
|
||||
invalid.Add(key is "page" or "pageSize" or "status" ? key : "query");
|
||||
}
|
||||
}
|
||||
|
||||
if (page < 1 && !invalid.Contains("page")) invalid.Add("page");
|
||||
if ((pageSize < 1 || pageSize > ContactAdminService.MaxPageSize) && !invalid.Contains("pageSize")) invalid.Add("pageSize");
|
||||
if (!string.IsNullOrWhiteSpace(status) && !ContactStatusNames.TryParseListable(status, out _) && !invalid.Contains("status")) invalid.Add("status");
|
||||
|
||||
if (invalid.Count > 0)
|
||||
{
|
||||
return ContactProblems.Invalid(options.Value.ProblemTypeBase, invalid.Distinct().ToArray());
|
||||
}
|
||||
|
||||
var result = await service.ListAsync(status, page, pageSize, cancellationToken);
|
||||
return result is null ? ContactProblems.Invalid(options.Value.ProblemTypeBase, "query") : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = await service.GetAsync(id, cancellationToken);
|
||||
return message is null ? NotFound() : Ok(message);
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}")]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SetStatus(
|
||||
Guid id, [FromBody] UpdateContactMessageStatusRequest? request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ModelState.IsValid || request is null || !ContactStatusNames.TryParseSettable(request.Status, out var status))
|
||||
{
|
||||
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "status");
|
||||
}
|
||||
|
||||
var message = await service.SetStatusAsync(id, status, cancellationToken);
|
||||
return message is null ? NotFound() : Ok(message);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
|
||||
=> await service.DeleteAsync(id, cancellationToken) ? NoContent() : NotFound();
|
||||
|
||||
[HttpPost("{id:guid}/resend")]
|
||||
[EnableRateLimiting(ResendPolicy)]
|
||||
[ProducesResponseType(typeof(ContactResendResult), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict, "application/problem+json")]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")]
|
||||
public async Task<IActionResult> Resend(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.ResendAsync(id, cancellationToken);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (ContactResendNotAllowedException ex)
|
||||
{
|
||||
return ContactProblems.Conflict(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The CMS switch of the contact form: a singleton resource. The form is open only when this
|
||||
/// switch AND the host switch are on. Default: off.
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(IgnoreApi = false)]
|
||||
[Route("contact-settings")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
[ServiceFilter(typeof(ContactAdminRouteFilter))]
|
||||
public class ContactSettingsController(IContactSettingsService service, IOptions<ContactOptions> options) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
|
||||
public async Task<IActionResult> Get(CancellationToken cancellationToken)
|
||||
=> Ok(await service.GetAsync(cancellationToken));
|
||||
|
||||
[HttpPut]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
|
||||
public async Task<IActionResult> Put([FromBody] UpdateContactSettingsRequest? request, CancellationToken cancellationToken)
|
||||
{
|
||||
// A missing or non-boolean 'enabled' (or an unreadable body) is reported as errors.enabled.
|
||||
if (!ModelState.IsValid || request?.Enabled is not { } enabled)
|
||||
{
|
||||
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "enabled");
|
||||
}
|
||||
|
||||
return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken));
|
||||
}
|
||||
|
||||
private Guid CallerId()
|
||||
{
|
||||
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Controllers;
|
||||
|
||||
/// <summary>The problem+json answers of the contact routes, in one place.</summary>
|
||||
internal static class ContactProblems
|
||||
{
|
||||
public const string ContentType = "application/problem+json";
|
||||
|
||||
/// <summary>A 400 with the contract's <c>errors</c> map (field name -> codes).</summary>
|
||||
public static ObjectResult Validation(IReadOnlyDictionary<string, string[]> errors, string? typeBase)
|
||||
{
|
||||
var baseUri = typeBase?.TrimEnd('/');
|
||||
var problem = new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value))
|
||||
{
|
||||
Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation",
|
||||
Title = "Validation failed",
|
||||
Status = StatusCodes.Status400BadRequest,
|
||||
};
|
||||
|
||||
return new ObjectResult(problem)
|
||||
{
|
||||
StatusCode = StatusCodes.Status400BadRequest,
|
||||
ContentTypes = { ContentType },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A 400 that names the given fields as <c>invalid</c>.</summary>
|
||||
public static ObjectResult Invalid(string? typeBase, params string[] fields)
|
||||
=> Validation(fields.ToDictionary(f => f, _ => new[] { "invalid" }), typeBase);
|
||||
|
||||
public static ObjectResult Conflict(string title) => new(new ProblemDetails
|
||||
{
|
||||
Status = StatusCodes.Status409Conflict,
|
||||
Title = title,
|
||||
})
|
||||
{
|
||||
StatusCode = StatusCodes.Status409Conflict,
|
||||
ContentTypes = { ContentType },
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
|
||||
{
|
||||
public DbSet<ContactMessage> ContactMessages => Set<ContactMessage>();
|
||||
public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();
|
||||
public DbSet<ContactSettings> ContactSettings => Set<ContactSettings>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -31,6 +32,16 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
|
||||
entity.HasIndex(e => e.RetentionUntil);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ContactSettings>(entity =>
|
||||
{
|
||||
entity.ToTable("ContactSettings");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Id).ValueGeneratedNever();
|
||||
entity.Property(e => e.Enabled).IsRequired();
|
||||
entity.Property(e => e.UpdatedAt).IsRequired();
|
||||
entity.Property(e => e.UpdatedByUserId).IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<IdempotencyRecord>(entity =>
|
||||
{
|
||||
entity.ToTable("ContactIdempotency");
|
||||
|
||||
@@ -56,3 +56,18 @@ public class IdempotencyRecord
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public int StatusCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The CMS-controlled on/off switch of the contact form (a singleton row, id 1). While no row
|
||||
/// exists the switch is off. It is the second layer of the gate; the host switch
|
||||
/// (<c>Contact:Enabled</c>) is the first.
|
||||
/// </summary>
|
||||
public class ContactSettings
|
||||
{
|
||||
public const int SingletonId = 1;
|
||||
|
||||
public int Id { get; set; } = SingletonId;
|
||||
public bool Enabled { get; set; }
|
||||
public DateTimeOffset UpdatedAt { get; set; }
|
||||
public Guid UpdatedByUserId { get; set; }
|
||||
}
|
||||
|
||||
Generated
+134
@@ -0,0 +1,134 @@
|
||||
// <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("20261109202158_AddContactSettings")]
|
||||
partial class AddContactSettings
|
||||
{
|
||||
/// <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")
|
||||
.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<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,37 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddContactSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ContactSettings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false),
|
||||
Enabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
UpdatedByUserId = table.Column<Guid>(type: "char(36)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ContactSettings", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ContactSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,25 @@ namespace SlpModularCms.Modules.Contact.Migrations
|
||||
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<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")
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Models;
|
||||
|
||||
// JSON shapes of the management routes. Statuses are lower-camel strings:
|
||||
// status: new | read | archived | spam | converted
|
||||
// mailStatus: pending | sent | failed | notApplicable
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactMessageListItem(
|
||||
string Id,
|
||||
DateTimeOffset ReceivedAt,
|
||||
string Name,
|
||||
string Email,
|
||||
string Subject,
|
||||
string Status,
|
||||
string MailStatus);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactMessageList(
|
||||
IReadOnlyList<ContactMessageListItem> Items,
|
||||
int Page,
|
||||
int PageSize,
|
||||
int TotalCount,
|
||||
int UnreadCount);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactMessageDetail(
|
||||
string Id,
|
||||
DateTimeOffset ReceivedAt,
|
||||
string Name,
|
||||
string Email,
|
||||
string Subject,
|
||||
string Message,
|
||||
string Status,
|
||||
string MailStatus,
|
||||
int MailAttempts,
|
||||
string? MailError,
|
||||
DateTimeOffset RetentionUntil);
|
||||
|
||||
/// <summary>Body of PATCH /contact-messages/{id}. Nullable so a missing field is reported in our own shape.</summary>
|
||||
public record UpdateContactMessageStatusRequest(string? Status);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>The wire names of the statuses.</summary>
|
||||
public static class ContactStatusNames
|
||||
{
|
||||
public static string Of(ContactMessageStatus status) => status switch
|
||||
{
|
||||
ContactMessageStatus.New => "new",
|
||||
ContactMessageStatus.Read => "read",
|
||||
ContactMessageStatus.Archived => "archived",
|
||||
ContactMessageStatus.Spam => "spam",
|
||||
ContactMessageStatus.Converted => "converted",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(status)),
|
||||
};
|
||||
|
||||
public static string Of(ContactMailStatus status) => status switch
|
||||
{
|
||||
ContactMailStatus.Pending => "pending",
|
||||
ContactMailStatus.Sent => "sent",
|
||||
ContactMailStatus.Failed => "failed",
|
||||
ContactMailStatus.NotApplicable => "notApplicable",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(status)),
|
||||
};
|
||||
|
||||
/// <summary>Parses a filter value (case-insensitive); only the statuses that can be listed.</summary>
|
||||
public static bool TryParseListable(string? value, out ContactMessageStatus status)
|
||||
{
|
||||
status = default;
|
||||
switch (value?.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "new": status = ContactMessageStatus.New; return true;
|
||||
case "read": status = ContactMessageStatus.Read; return true;
|
||||
case "archived": status = ContactMessageStatus.Archived; return true;
|
||||
case "spam": status = ContactMessageStatus.Spam; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses a value an administrator may set: new, read or archived.</summary>
|
||||
public static bool TryParseSettable(string? value, out ContactMessageStatus status)
|
||||
=> TryParseListable(value, out status) && status != ContactMessageStatus.Spam;
|
||||
}
|
||||
@@ -13,6 +13,21 @@ public interface IContactRepository
|
||||
Task SaveChangesAsync(CancellationToken cancellationToken);
|
||||
Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken);
|
||||
Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
|
||||
|
||||
// ---- management (admin) ----
|
||||
|
||||
/// <summary>One page of messages of the given statuses, newest first, plus the total count of that selection.</summary>
|
||||
Task<(IReadOnlyList<ContactMessage> Items, int TotalCount)> ListAsync(
|
||||
string siteId, IReadOnlyCollection<ContactMessageStatus> statuses, int skip, int take, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Messages with status New. Spam is never counted.</summary>
|
||||
Task<int> CountUnreadAsync(string siteId, CancellationToken cancellationToken);
|
||||
|
||||
Task<ContactMessage?> GetAsync(string siteId, Guid id, CancellationToken cancellationToken);
|
||||
void Remove(ContactMessage message);
|
||||
|
||||
Task<ContactSettings?> GetSettingsAsync(CancellationToken cancellationToken);
|
||||
void Add(ContactSettings settings);
|
||||
}
|
||||
|
||||
public class ContactRepository(ContactDbContext context) : IContactRepository
|
||||
@@ -33,6 +48,52 @@ public class ContactRepository(ContactDbContext context) : IContactRepository
|
||||
|
||||
public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
public async Task<(IReadOnlyList<ContactMessage> Items, int TotalCount)> ListAsync(
|
||||
string siteId, IReadOnlyCollection<ContactMessageStatus> statuses, int skip, int take, CancellationToken cancellationToken)
|
||||
{
|
||||
// One flag per status instead of 'statuses.Contains(m.Status)': the status is stored as a
|
||||
// string through a value converter, and a parameterized collection loses that mapping in
|
||||
// the SQL translation.
|
||||
var wantNew = statuses.Contains(ContactMessageStatus.New);
|
||||
var wantRead = statuses.Contains(ContactMessageStatus.Read);
|
||||
var wantArchived = statuses.Contains(ContactMessageStatus.Archived);
|
||||
var wantSpam = statuses.Contains(ContactMessageStatus.Spam);
|
||||
var wantConverted = statuses.Contains(ContactMessageStatus.Converted);
|
||||
|
||||
var query = context.ContactMessages
|
||||
.AsNoTracking()
|
||||
.Where(m => m.SiteId == siteId
|
||||
&& ((wantNew && m.Status == ContactMessageStatus.New)
|
||||
|| (wantRead && m.Status == ContactMessageStatus.Read)
|
||||
|| (wantArchived && m.Status == ContactMessageStatus.Archived)
|
||||
|| (wantSpam && m.Status == ContactMessageStatus.Spam)
|
||||
|| (wantConverted && m.Status == ContactMessageStatus.Converted)));
|
||||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var items = await query
|
||||
.OrderByDescending(m => m.ReceivedAt)
|
||||
.ThenBy(m => m.Id)
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return (items, total);
|
||||
}
|
||||
|
||||
public Task<int> CountUnreadAsync(string siteId, CancellationToken cancellationToken)
|
||||
=> context.ContactMessages.CountAsync(
|
||||
m => m.SiteId == siteId && m.Status == ContactMessageStatus.New, cancellationToken);
|
||||
|
||||
public Task<ContactMessage?> GetAsync(string siteId, Guid id, CancellationToken cancellationToken)
|
||||
=> context.ContactMessages.FirstOrDefaultAsync(m => m.SiteId == siteId && m.Id == id, cancellationToken);
|
||||
|
||||
public void Remove(ContactMessage message) => context.ContactMessages.Remove(message);
|
||||
|
||||
public Task<ContactSettings?> GetSettingsAsync(CancellationToken cancellationToken)
|
||||
=> context.ContactSettings.FirstOrDefaultAsync(s => s.Id == ContactSettings.SingletonId, cancellationToken);
|
||||
|
||||
public void Add(ContactSettings settings) => context.ContactSettings.Add(settings);
|
||||
|
||||
public async Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var total = 0;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Models;
|
||||
using SlpModularCms.Modules.Contact.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
/// <summary>Thrown when a spam message is resent; it must be marked as not spam first.</summary>
|
||||
public sealed class ContactResendNotAllowedException() : Exception("A spam message cannot be resent; mark it as not spam first.");
|
||||
|
||||
public interface IContactAdminService
|
||||
{
|
||||
/// <summary>Null when page or pageSize is out of range or the status filter is unknown (the caller reports 400).</summary>
|
||||
Task<ContactMessageList?> ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken);
|
||||
|
||||
Task<ContactMessageDetail?> GetAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Null when the message does not exist.</summary>
|
||||
Task<ContactMessageDetail?> SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken);
|
||||
|
||||
Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Null when the message does not exist. Throws <see cref="ContactResendNotAllowedException"/> for spam.</summary>
|
||||
Task<ContactResendResult?> ResendAsync(Guid id, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Everything an administrator does with the stored messages. Spam is kept apart: it is never in
|
||||
/// the default list and never counted as unread. Nothing personal is logged, only ids and outcomes.
|
||||
/// </summary>
|
||||
public sealed class ContactAdminService(
|
||||
IContactRepository repository,
|
||||
IContactMailSender mailSender,
|
||||
IOptions<ContactOptions> options,
|
||||
TimeProvider time,
|
||||
ILogger<ContactAdminService> logger) : IContactAdminService
|
||||
{
|
||||
public const int DefaultPageSize = 25;
|
||||
public const int MaxPageSize = 100;
|
||||
|
||||
private static readonly ContactMessageStatus[] DefaultStatuses =
|
||||
[ContactMessageStatus.New, ContactMessageStatus.Read, ContactMessageStatus.Archived];
|
||||
|
||||
public async Task<ContactMessageList?> ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken)
|
||||
{
|
||||
if (page < 1 || pageSize < 1 || pageSize > MaxPageSize)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
ContactMessageStatus[] statuses;
|
||||
if (string.IsNullOrWhiteSpace(status))
|
||||
{
|
||||
statuses = DefaultStatuses;
|
||||
}
|
||||
else if (ContactStatusNames.TryParseListable(status, out var parsed))
|
||||
{
|
||||
statuses = [parsed];
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var siteId = options.Value.EffectiveSiteId;
|
||||
var (items, total) = await repository.ListAsync(siteId, statuses, (page - 1) * pageSize, pageSize, cancellationToken);
|
||||
var unread = await repository.CountUnreadAsync(siteId, cancellationToken);
|
||||
|
||||
return new ContactMessageList(
|
||||
items.Select(m => new ContactMessageListItem(
|
||||
m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject,
|
||||
ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus))).ToList(),
|
||||
page, pageSize, total, unread);
|
||||
}
|
||||
|
||||
public async Task<ContactMessageDetail?> GetAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
|
||||
return message is null ? null : ToDetail(message);
|
||||
}
|
||||
|
||||
public async Task<ContactMessageDetail?> SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
|
||||
if (message is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Marking a spam message as read/new/archived means "this was a real person": it then
|
||||
// follows the normal retention instead of being deleted after the short spam period.
|
||||
if (message.Status == ContactMessageStatus.Spam)
|
||||
{
|
||||
message.RetentionUntil = time.GetUtcNow().AddMonths(options.Value.RetentionMonths);
|
||||
}
|
||||
|
||||
message.Status = status;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Contact message {MessageId} set to {Status}", message.Id, status);
|
||||
return ToDetail(message);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
|
||||
if (message is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
repository.Remove(message);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Contact message {MessageId} deleted", id);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<ContactResendResult?> ResendAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
|
||||
if (message is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (message.Status == ContactMessageStatus.Spam)
|
||||
{
|
||||
throw new ContactResendNotAllowedException();
|
||||
}
|
||||
|
||||
var outcome = await mailSender.SendAsync(message, cancellationToken);
|
||||
if (outcome != ContactMailOutcome.Skipped)
|
||||
{
|
||||
message.MailAttempts++;
|
||||
message.MailStatus = outcome == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, outcome);
|
||||
return new ContactResendResult(
|
||||
ContactStatusNames.Of(message.MailStatus), message.MailAttempts, outcome == ContactMailOutcome.Sent);
|
||||
}
|
||||
|
||||
private static ContactMessageDetail ToDetail(ContactMessage m) => new(
|
||||
m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, m.Message,
|
||||
ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus),
|
||||
m.MailAttempts, m.MailError, m.RetentionUntil);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
using SlpModularCms.Modules.Contact.Models;
|
||||
using SlpModularCms.Modules.Contact.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The latest known value of the CMS switch, shared by all requests of this process. Short-lived
|
||||
/// so the public routes do not query the database on every request, and dropped immediately when
|
||||
/// the switch is changed here (other instances see a change after at most <see cref="Lifetime"/>).
|
||||
/// </summary>
|
||||
public sealed class ContactSettingsCache(TimeProvider time)
|
||||
{
|
||||
public static readonly TimeSpan Lifetime = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly object _lock = new();
|
||||
private bool _value;
|
||||
private DateTimeOffset _expires = DateTimeOffset.MinValue;
|
||||
|
||||
public bool TryGet(out bool enabled)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
enabled = _value;
|
||||
return time.GetUtcNow() < _expires;
|
||||
}
|
||||
}
|
||||
|
||||
public void Set(bool enabled)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_value = enabled;
|
||||
_expires = time.GetUtcNow() + Lifetime;
|
||||
}
|
||||
}
|
||||
|
||||
public void Invalidate()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_expires = DateTimeOffset.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface IContactSettingsService
|
||||
{
|
||||
/// <summary>The CMS switch (a missing row means off).</summary>
|
||||
Task<bool> IsEnabledAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken);
|
||||
Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class ContactSettingsService(
|
||||
IContactRepository repository,
|
||||
ContactSettingsCache cache,
|
||||
IOptions<ContactOptions> options,
|
||||
TimeProvider time) : IContactSettingsService
|
||||
{
|
||||
public async Task<bool> IsEnabledAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (cache.TryGet(out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
|
||||
cache.Set(enabled);
|
||||
return enabled;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public async Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = await repository.GetSettingsAsync(cancellationToken);
|
||||
if (settings is null)
|
||||
{
|
||||
settings = new ContactSettings();
|
||||
repository.Add(settings);
|
||||
}
|
||||
|
||||
settings.Enabled = enabled;
|
||||
settings.UpdatedAt = time.GetUtcNow();
|
||||
settings.UpdatedByUserId = userId;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
cache.Invalidate();
|
||||
return new ContactSettingsDto(enabled, options.Value.Enabled);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Layer 2: the switch an administrator controls in the CMS.</summary>
|
||||
public sealed class CmsFlagContactFormGate(IContactSettingsService settings) : IContactFormGate
|
||||
{
|
||||
public Task<bool> IsOpenAsync(CancellationToken cancellationToken) => settings.IsEnabledAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The form is open only if every layer is open. Layers are asked in order and the first closed
|
||||
/// one ends the check, so with the host switch off the database is never touched.
|
||||
/// </summary>
|
||||
public sealed class CompositeContactFormGate(IReadOnlyList<IContactFormGate> layers) : IContactFormGate
|
||||
{
|
||||
public async Task<bool> IsOpenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var layer in layers)
|
||||
{
|
||||
if (!await layer.IsOpenAsync(cancellationToken))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user