Vertaalbestanden 3/6: Identity- en Availability-meldingen naar de tekstbestanden (core.identity.*, availability.*)

Nederlandse tekst ongewijzigd (tests op exacte tekst). De uitzondering MasterControlledAvailabilityException krijgt een technische Engelse melding; de zin voor de beheerder komt uit availability.masterControlled.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 20:41:32 +01:00
co-authored by Claude Sonnet 5.5
parent 000d0a61b4
commit 3c3a29bacc
20 changed files with 210 additions and 24 deletions
@@ -10,4 +10,25 @@ public class CoreTextsTests
[Fact]
public void TheCoreTextFiles_MatchTheDeclaredKeys_InDutchAndEnglish()
=> TextAudit.Verify(typeof(TextCatalog).Assembly, TextAudit.KeysOf(typeof(CoreTexts)), "nl", "en").Should().BeEmpty();
[Theory]
[InlineData("core.identity.auth.invalidCredentials", "Ongeldige inloggegevens.")]
[InlineData("core.identity.auth.invalidRefreshToken", "Ongeldig refresh token.")]
[InlineData("core.identity.auth.tokenReuse", "Mogelijk token misbruik gedetecteerd. Alle sessies zijn beëindigd.")]
[InlineData("core.identity.auth.userNotFound", "Gebruiker niet gevonden.")]
[InlineData("core.identity.invitation.userExists", "Er bestaat al een gebruiker met dit e-mailadres.")]
[InlineData("core.identity.invitation.openInvitation", "Er staat al een openstaande uitnodiging voor dit e-mailadres.")]
[InlineData("core.identity.invitation.invalid", "Ongeldige of verlopen uitnodiging.")]
[InlineData("core.identity.invitation.accepted", "Account succesvol ingesteld. Je kunt nu inloggen.")]
[InlineData("core.identity.setup.alreadyInitialized", "Systeem is al geïnitialiseerd.")]
[InlineData("core.identity.setup.completed", "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt.")]
public void TheDutchIdentityMessages_AreTheOnesThatWereInTheCode(string key, string expected)
=> TextCatalog.Default.Get(new TextKey(key)).Should().Be(expected);
[Fact]
public void TheMessagesThatCarryTheErrorsOfTheIdentityStore_KeepTheirFormat()
{
TextCatalog.Default.Get(CoreTexts.Identity.Invitation.CreateFailed, args: ("errors", "a, b")).Should().Be("Kan gebruiker niet aanmaken: a, b");
TextCatalog.Default.Get(CoreTexts.Identity.Setup.CreateOwnerFailed, args: ("errors", "a, b")).Should().Be("Fout bij aanmaken eigenaar: a, b");
}
}
@@ -4,10 +4,11 @@ namespace SlpModularCms.Core.Availability;
/// Thrown when an attempt is made to change the local availability status while a
/// master CMS has taken control of this instance's gate (e.g. set it to NotAvailable).
/// The local status change would have no visible effect since the master gate
/// overrides it, so it's rejected outright instead of silently doing nothing.
/// overrides it, so it's rejected outright instead of silently doing nothing. The message is technical (logs); the
/// sentence shown to the administrator is the text <c>availability.masterControlled</c>.
/// </summary>
public class MasterControlledAvailabilityException(string? masterDisableMessage)
: InvalidOperationException("De beschikbaarheid van dit systeem wordt beheerd door de Master-CMS en kan hier niet worden gewijzigd.")
: InvalidOperationException("Availability is controlled by the master CMS and cannot be changed locally.")
{
public string? MasterDisableMessage { get; } = masterDisableMessage;
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
@@ -22,13 +23,16 @@ public class AuthService : IAuthService
private readonly ApplicationDbContext _context;
private readonly JwtSettings _jwtSettings;
private readonly ILogger<AuthService> _logger;
private readonly ITextCatalog _texts;
public AuthService(
UserManager<ApplicationUser> userManager,
ApplicationDbContext context,
IOptions<JwtSettings> jwtSettings,
ILogger<AuthService> logger)
ILogger<AuthService> logger,
ITextCatalog? texts = null)
{
_texts = texts ?? TextCatalog.Default;
_userManager = userManager;
_context = context;
_jwtSettings = jwtSettings.Value;
@@ -45,7 +49,7 @@ public class AuthService : IAuthService
// password, the attempted password, and the address itself.
SecurityEvents.FailedLogin(_logger, "/api/v1/Auth/login", accountExists: user is not null);
throw new UnauthorizedException("Ongeldige inloggegevens.");
throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Auth.InvalidCredentials));
}
return await GenerateTokenResponseAsync(user);
@@ -59,7 +63,7 @@ public class AuthService : IAuthService
if (savedRefreshToken == null || !savedRefreshToken.IsActive)
{
throw new UnauthorizedException("Ongeldig refresh token.");
throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Auth.InvalidRefreshToken));
}
if (savedRefreshToken.IsUsed)
@@ -69,7 +73,7 @@ public class AuthService : IAuthService
var allTokens = await _context.RefreshTokens.Where(t => t.UserId == userId).ToListAsync();
foreach (var token in allTokens) token.IsRevoked = true;
await _context.SaveChangesAsync();
throw new UnauthorizedException("Mogelijk token misbruik gedetecteerd. Alle sessies zijn beëindigd.");
throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Auth.TokenReuse));
}
if (!savedRefreshToken.User.IsActive)
@@ -77,7 +81,7 @@ public class AuthService : IAuthService
// A deactivated account must not get a new access token from a still-valid refresh token.
savedRefreshToken.IsRevoked = true;
await _context.SaveChangesAsync();
throw new UnauthorizedException("Ongeldig refresh token.");
throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Auth.InvalidRefreshToken));
}
savedRefreshToken.IsUsed = true;
@@ -99,7 +103,7 @@ public class AuthService : IAuthService
public async Task ChangePasswordAsync(Guid userId, string currentPassword, string newPassword)
{
var user = await _userManager.FindByIdAsync(userId.ToString())
?? throw new UnauthorizedException("Gebruiker niet gevonden.");
?? throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Auth.UserNotFound));
var result = await _userManager.ChangePasswordAsync(user, currentPassword, newPassword);
if (!result.Succeeded)
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
@@ -15,12 +16,15 @@ public class InvitationService : IInvitationService
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly InvitationSettings _settings;
private readonly ITextCatalog _texts;
public InvitationService(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
IOptions<InvitationSettings> settings)
IOptions<InvitationSettings> settings,
ITextCatalog? texts = null)
{
_texts = texts ?? TextCatalog.Default;
_context = context;
_userManager = userManager;
_settings = settings.Value;
@@ -31,7 +35,7 @@ public class InvitationService : IInvitationService
var user = await _userManager.FindByEmailAsync(email);
if (user != null)
{
throw new InvitationOrUserAlreadyExistsException("Er bestaat al een gebruiker met dit e-mailadres.");
throw new InvitationOrUserAlreadyExistsException(_texts.Get(CoreTexts.Identity.Invitation.UserExists));
}
var normalized = email.ToLower();
@@ -42,7 +46,7 @@ public class InvitationService : IInvitationService
if (invitationsForEmail.Any(i => !i.IsAccepted && !i.IsExpired))
{
throw new InvitationOrUserAlreadyExistsException(
"Er staat al een openstaande uitnodiging voor dit e-mailadres.");
_texts.Get(CoreTexts.Identity.Invitation.OpenInvitation));
}
// What is left is stale: an expired invitation, or an accepted one whose user no longer
@@ -81,7 +85,7 @@ public class InvitationService : IInvitationService
var invitation = await _context.Invitations.FirstOrDefaultAsync(i => i.Token == token);
if (invitation == null || invitation.IsAccepted || invitation.IsExpired)
{
throw new UnauthorizedException("Ongeldige of verlopen uitnodiging.");
throw new UnauthorizedException(_texts.Get(CoreTexts.Identity.Invitation.Invalid));
}
var user = new ApplicationUser
@@ -96,7 +100,7 @@ public class InvitationService : IInvitationService
var result = await _userManager.CreateAsync(user, password);
if (!result.Succeeded)
{
throw new ValidationException("Kan gebruiker niet aanmaken: " + string.Join(", ", result.Errors.Select(e => e.Description)));
throw new ValidationException(_texts.Get(CoreTexts.Identity.Invitation.CreateFailed, args: ("errors", string.Join(", ", result.Errors.Select(e => e.Description)))));
}
await _userManager.AddToRoleAsync(user, invitation.Role);
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Core.Exceptions;
@@ -16,8 +17,11 @@ public class SetupService : ISetupService
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public SetupService(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
private readonly ITextCatalog _texts;
public SetupService(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ITextCatalog? texts = null)
{
_texts = texts ?? TextCatalog.Default;
_userManager = userManager;
_roleManager = roleManager;
}
@@ -31,7 +35,7 @@ public class SetupService : ISetupService
{
if (await IsSystemInitializedAsync())
{
throw new ValidationException("Systeem is al geïnitialiseerd.");
throw new ValidationException(_texts.Get(CoreTexts.Identity.Setup.AlreadyInitialized));
}
// Zorg dat rollen bestaan
@@ -55,7 +59,7 @@ public class SetupService : ISetupService
var result = await _userManager.CreateAsync(user, password);
if (!result.Succeeded)
{
throw new ValidationException("Fout bij aanmaken eigenaar: " + string.Join(", ", result.Errors.Select(e => e.Description)));
throw new ValidationException(_texts.Get(CoreTexts.Identity.Setup.CreateOwnerFailed, args: ("errors", string.Join(", ", result.Errors.Select(e => e.Description)))));
}
await _userManager.AddToRoleAsync(user, "Owner");
+28
View File
@@ -6,6 +6,34 @@ namespace SlpModularCms.Core.Texts;
/// </summary>
public static class CoreTexts
{
/// <summary>Messages of sign-in, invitations and first-time setup (shown to the administrator). Key path <c>core.identity.*</c>.</summary>
public static class Identity
{
public static class Auth
{
public static readonly TextKey InvalidCredentials = new("core.identity.auth.invalidCredentials");
public static readonly TextKey InvalidRefreshToken = new("core.identity.auth.invalidRefreshToken");
public static readonly TextKey TokenReuse = new("core.identity.auth.tokenReuse");
public static readonly TextKey UserNotFound = new("core.identity.auth.userNotFound");
}
public static class Invitation
{
public static readonly TextKey UserExists = new("core.identity.invitation.userExists");
public static readonly TextKey OpenInvitation = new("core.identity.invitation.openInvitation");
public static readonly TextKey Invalid = new("core.identity.invitation.invalid");
public static readonly TextKey CreateFailed = new("core.identity.invitation.createFailed", "errors");
public static readonly TextKey Accepted = new("core.identity.invitation.accepted");
}
public static class Setup
{
public static readonly TextKey AlreadyInitialized = new("core.identity.setup.alreadyInitialized");
public static readonly TextKey CreateOwnerFailed = new("core.identity.setup.createOwnerFailed", "errors");
public static readonly TextKey Completed = new("core.identity.setup.completed");
}
}
/// <summary>Mails sent by the CMS (invitations, password reset, account changes, contact message). Key path <c>core.mail.*</c>.</summary>
public static class Mail
{
+12
View File
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace SlpModularCms.Core.Texts;
/// <summary>The catalogue of the current request (controllers and middleware), without extra constructor parameters.</summary>
public static class HttpTexts
{
/// <summary>The configured catalogue of the request's services; the shared default one when there is none (unit tests).</summary>
public static ITextCatalog From(HttpContext? context)
=> context?.RequestServices?.GetService<ITextCatalog>() ?? TextCatalog.Default;
}
@@ -98,6 +98,14 @@ public sealed partial class TextCatalog : ITextCatalog
[],
Microsoft.Extensions.Logging.Abstractions.NullLogger<TextCatalog>.Instance);
private static readonly Lazy<TextCatalog> DefaultInstance = new(() => CreateDefault());
/// <summary>
/// A shared catalogue over Core's own texts in Dutch, for code that is not given the real one (unit tests, a service
/// constructed by hand). The hosts always inject the configured catalogue.
/// </summary>
public static TextCatalog Default => DefaultInstance.Value;
/// <summary>The languages that have embedded texts.</summary>
public IReadOnlyCollection<string> Languages => _embedded.Keys;
+20
View File
@@ -57,6 +57,26 @@
"heading": "New message from the contact form",
"intro": "A message was sent through the contact form of {site}."
}
},
"identity": {
"auth": {
"invalidCredentials": "Invalid credentials.",
"invalidRefreshToken": "Invalid refresh token.",
"tokenReuse": "Possible token abuse detected. All sessions have been ended.",
"userNotFound": "User not found."
},
"invitation": {
"userExists": "A user with this e-mail address already exists.",
"openInvitation": "There is already an open invitation for this e-mail address.",
"invalid": "Invalid or expired invitation.",
"createFailed": "Could not create the user: {errors}",
"accepted": "Account set up successfully. You can sign in now."
},
"setup": {
"alreadyInitialized": "The system has already been initialised.",
"createOwnerFailed": "Could not create the owner: {errors}",
"completed": "System initialised successfully. The first owner has been created."
}
}
}
}
+20
View File
@@ -57,6 +57,26 @@
"heading": "Nieuw bericht via het contactformulier",
"intro": "Er is een bericht verstuurd via het contactformulier van {site}."
}
},
"identity": {
"auth": {
"invalidCredentials": "Ongeldige inloggegevens.",
"invalidRefreshToken": "Ongeldig refresh token.",
"tokenReuse": "Mogelijk token misbruik gedetecteerd. Alle sessies zijn beëindigd.",
"userNotFound": "Gebruiker niet gevonden."
},
"invitation": {
"userExists": "Er bestaat al een gebruiker met dit e-mailadres.",
"openInvitation": "Er staat al een openstaande uitnodiging voor dit e-mailadres.",
"invalid": "Ongeldige of verlopen uitnodiging.",
"createFailed": "Kan gebruiker niet aanmaken: {errors}",
"accepted": "Account succesvol ingesteld. Je kunt nu inloggen."
},
"setup": {
"alreadyInitialized": "Systeem is al geïnitialiseerd.",
"createOwnerFailed": "Fout bij aanmaken eigenaar: {errors}",
"completed": "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt."
}
}
}
}
@@ -0,0 +1,23 @@
using FluentAssertions;
using SlpModularCms.Core.Texts;
using Xunit;
namespace SlpModularCms.Modules.Availability.Tests;
public class AvailabilityTextsTests
{
private static readonly TextCatalog Catalog = TextCatalog.CreateDefault(typeof(AvailabilityTexts).Assembly);
[Fact]
public void TheTextFiles_MatchTheDeclaredKeys_InDutchAndEnglish()
=> TextAudit.Verify(typeof(AvailabilityTexts).Assembly, TextAudit.KeysOf(typeof(AvailabilityTexts)), "nl", "en").Should().BeEmpty();
[Theory]
[InlineData("masterControlled", "De beschikbaarheid van dit systeem wordt beheerd door de Master-CMS en kan hier niet worden gewijzigd.")]
[InlineData("unavailable", "De service is tijdelijk niet beschikbaar.")]
[InlineData("maintenance", "Het systeem is momenteel in onderhoud. Probeer het later opnieuw.")]
[InlineData("sessionExpired", "De sessie is verlopen. Ververs de sessie en probeer het opnieuw.")]
[InlineData("statusUpdateUnsupported", "Status update niet ondersteund door huidige service.")]
public void TheDutchTexts_AreTheOnesThatWereInTheCode(string key, string expected)
=> Catalog.Get(new TextKey("availability." + key)).Should().Be(expected);
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
@@ -24,6 +25,7 @@ public class AvailabilityModule : IModule
public void RegisterServices(IServiceCollection services)
{
services.AddCmsTextsFrom(typeof(AvailabilityModule).Assembly);
services.AddScoped<IAvailabilityService, PersistentAvailabilityService>();
services.AddScoped<PersistentAvailabilityService>();
@@ -0,0 +1,13 @@
using SlpModularCms.Core.Texts;
namespace SlpModularCms.Modules.Availability;
/// <summary>The keys of the Availability module's texts (<c>Texts/nl.json</c>, <c>Texts/en.json</c>, key path <c>availability.*</c>).</summary>
public static class AvailabilityTexts
{
public static readonly TextKey MasterControlled = new("availability.masterControlled");
public static readonly TextKey Unavailable = new("availability.unavailable");
public static readonly TextKey Maintenance = new("availability.maintenance");
public static readonly TextKey SessionExpired = new("availability.sessionExpired");
public static readonly TextKey StatusUpdateUnsupported = new("availability.statusUpdateUnsupported");
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -40,7 +41,7 @@ public class AvailabilityController : ControllerBase
{
if (_availabilityService is not PersistentAvailabilityService persistentService)
{
return BadRequest("Status update niet ondersteund door huidige service.");
return BadRequest(HttpTexts.From(HttpContext).Get(AvailabilityTexts.StatusUpdateUnsupported));
}
try
@@ -57,7 +58,7 @@ public class AvailabilityController : ControllerBase
return Conflict(new ProblemDetails
{
Status = StatusCodes.Status409Conflict,
Title = ex.Message,
Title = HttpTexts.From(HttpContext).Get(AvailabilityTexts.MasterControlled),
});
}
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
@@ -102,7 +103,7 @@ public class AvailabilityMiddleware
{
Status = StatusCodes.Status503ServiceUnavailable,
Title = "Service Unavailable",
Detail = masterStatus.DisableMessage ?? "De service is tijdelijk niet beschikbaar.",
Detail = masterStatus.DisableMessage ?? HttpTexts.From(context).Get(AvailabilityTexts.Unavailable),
Instance = context.Request.Path
});
return;
@@ -123,8 +124,8 @@ public class AvailabilityMiddleware
Status = StatusCodes.Status503ServiceUnavailable,
Title = "Service Unavailable",
Detail = status == AvailabilityStatus.Maintenance
? "Het systeem is momenteel in onderhoud. Probeer het later opnieuw."
: "De service is tijdelijk niet beschikbaar.",
? HttpTexts.From(context).Get(AvailabilityTexts.Maintenance)
: HttpTexts.From(context).Get(AvailabilityTexts.Unavailable),
Instance = context.Request.Path
});
}
@@ -169,7 +170,7 @@ public class AvailabilityMiddleware
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Detail = "De sessie is verlopen. Ververs de sessie en probeer het opnieuw.",
Detail = HttpTexts.From(context).Get(AvailabilityTexts.SessionExpired),
Instance = context.Request.Path
});
return true;
@@ -16,4 +16,8 @@
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Texts\*.json" WithCulture="false" />
</ItemGroup>
</Project>
@@ -0,0 +1,9 @@
{
"availability": {
"masterControlled": "The availability of this system is managed by the master CMS and cannot be changed here.",
"unavailable": "The service is temporarily unavailable.",
"maintenance": "The system is currently under maintenance. Please try again later.",
"sessionExpired": "The session has expired. Refresh the session and try again.",
"statusUpdateUnsupported": "Status update is not supported by the current service."
}
}
@@ -0,0 +1,9 @@
{
"availability": {
"masterControlled": "De beschikbaarheid van dit systeem wordt beheerd door de Master-CMS en kan hier niet worden gewijzigd.",
"unavailable": "De service is tijdelijk niet beschikbaar.",
"maintenance": "Het systeem is momenteel in onderhoud. Probeer het later opnieuw.",
"sessionExpired": "De sessie is verlopen. Ververs de sessie en probeer het opnieuw.",
"statusUpdateUnsupported": "Status update niet ondersteund door huidige service."
}
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@@ -46,6 +47,6 @@ public class InvitationController : ControllerBase
public async Task<IActionResult> Complete([FromBody] CompleteSetupRequest request)
{
await _invitationService.CompleteInvitationAsync(request.Token, request.Password, request.Name);
return Ok(new { message = "Account succesvol ingesteld. Je kunt nu inloggen." });
return Ok(new { message = HttpTexts.From(HttpContext).Get(CoreTexts.Identity.Invitation.Accepted) });
}
}
@@ -1,3 +1,4 @@
using SlpModularCms.Core.Texts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
@@ -52,6 +53,6 @@ public class SetupController : ControllerBase
}
await _setupService.CreateInitialOwnerAsync(request.Name, request.Email, request.Password);
return Ok(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." });
return Ok(new { Message = HttpTexts.From(HttpContext).Get(CoreTexts.Identity.Setup.Completed) });
}
}