From 149f81a47938c8009ec8ccb035031c64665c309e Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Sun, 8 Nov 2026 19:10:44 +0100 Subject: [PATCH] U2 identity-mail-flows (backend): taal per gebruiker, uitnodigingsmail, opnieuw versturen, meldingen, stamp-controle Kolommen Users.PreferredLanguage en Invitations.Language (additieve migratie). IdentityMailService verstuurt uitnodiging, nieuwe link en meldingen bij deactiveren, heractiveren en rolwijziging; een mailfout laat nooit een actie falen, het resultaat gaat mee in de respons naast de kopieerbare link. Nieuwe actie resend-invite. De security stamp zit in het access token en wordt vergeleken in de actief-controle: een wachtwoordwijziging beeindigt eerder uitgegeven access tokens, de refresh geeft stil een nieuw token. Co-Authored-By: Claude Sonnet 5.5 --- .../Email/IdentityMailServiceTests.cs | 166 ++++++ .../Email/MigrationRoundTripTests.cs | 21 +- .../Identity/DeactivatedUserAccessTests.cs | 49 +- .../Identity/InvitationServiceTests.cs | 28 ++ .../SessionEndsOnPasswordChangeTests.cs | 122 +++++ .../Data/ApplicationDbContext.cs | 7 +- .../Email/EmailServiceCollectionExtensions.cs | 1 + .../Email/IdentityMailService.cs | 105 ++++ .../ActiveUserTokenValidation.cs | 19 +- .../Identity/Entities/ApplicationUser.cs | 5 + .../Identity/Entities/Invitation.cs | 4 + .../Identity/Models/IdentityRequests.cs | 9 +- .../Identity/Models/TokenResponse.cs | 3 +- .../Identity/Services/AuthService.cs | 9 +- .../Identity/Services/IInvitationService.cs | 2 +- .../Identity/Services/InvitationService.cs | 7 +- ...08180809_AddLanguagePreference.Designer.cs | 474 ++++++++++++++++++ .../20261108180809_AddLanguagePreference.cs | 40 ++ .../ApplicationDbContextModelSnapshot.cs | 8 + .../Controllers/UsersControllerMailTests.cs | 334 ++++++++++++ .../UsersControllerRoleHierarchyTests.cs | 3 +- .../Controllers/UsersControllerTests.cs | 12 +- .../Controllers/UsersController.cs | 100 +++- 23 files changed, 1491 insertions(+), 37 deletions(-) create mode 100644 src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Identity/SessionEndsOnPasswordChangeTests.cs create mode 100644 src/SlpModularCms.Core/Email/IdentityMailService.cs create mode 100644 src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.Designer.cs create mode 100644 src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.cs create mode 100644 src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerMailTests.cs diff --git a/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs new file mode 100644 index 0000000..8881441 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs @@ -0,0 +1,166 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using SlpModularCms.Core.Email; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.SiteSettings; + +namespace SlpModularCms.Core.Tests.Email; + +internal sealed class CapturingSender : IEmailSender +{ + public List Sent { get; } = []; + public MailSendResult Result { get; set; } = MailSendResult.Ok; + public bool Throw { get; set; } + + public Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default) + { + if (Throw) throw new InvalidOperationException("boom with secret@example.org"); + Sent.Add(mail); + return Task.FromResult(Result); + } +} + +public class IdentityMailServiceTests +{ + private readonly CapturingSender _sender = new(); + private readonly ISiteSettingsService _settings = Substitute.For(); + + public IdentityMailServiceTests() => + _settings.GetEffectiveSenderAsync(Arg.Any()).Returns(("info@andreaslop.nl", "Andrea Slop Fotografie")); + + private IdentityMailService Service(string smtpHost = "mail.example.nl", string defaultLanguage = "nl", int hours = 24, string logo = "/admin/brand-logo-on-light.png") => + new(_sender, new MailTemplateRenderer(), + new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" })), + _settings, + Options.Create(new EmailOptions { LogoUrl = logo, BrandColor = "#5f6a58", Smtp = { Host = smtpHost } }), + Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" }), + Options.Create(new InvitationSettings { ExpiryHours = hours }), + NullLogger.Instance); + + [Fact] + public async Task Invitation_HasTheAdminLink_TheSiteSender_TheLogo_AndTheLifetime() + { + var result = await Service().SendInvitationAsync("new@example.org", "tok/en+1=", "nl", isNewLink: false); + + result.Sent.Should().BeTrue(); + var mail = _sender.Sent.Should().ContainSingle().Subject; + mail.ToAddress.Should().Be("new@example.org"); + mail.FromAddress.Should().Be("info@andreaslop.nl"); + mail.FromName.Should().Be("Andrea Slop Fotografie"); + mail.Subject.Should().Be("Uitnodiging voor Andrea Slop Fotografie"); + mail.HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D") + .And.Contain("https://test.andreaslop.nl/admin/brand-logo-on-light.png") + .And.Contain("24 uur").And.Contain("#5f6a58"); + mail.TextBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D"); + } + + [Fact] + public async Task ANewLink_UsesTheNewLinkText_AndTheConfiguredLifetime() + { + await Service(hours: 48).SendInvitationAsync("new@example.org", "t", "nl", isNewLink: true); + + var mail = _sender.Sent.Single(); + mail.Subject.Should().StartWith("Nieuwe uitnodigingslink"); + mail.HtmlBody.Should().Contain("48 uur"); + } + + [Theory] + [InlineData("en", "nl", "Invitation to")] + [InlineData(null, "en", "Invitation to")] + [InlineData(null, "nl", "Uitnodiging voor")] + [InlineData("nl", "en", "Uitnodiging voor")] + [InlineData("xx", "en", "Invitation to")] + public async Task TheLanguage_IsTheChosenOne_ElseTheSiteDefault(string? chosen, string siteDefault, string subjectStart) + { + await Service(defaultLanguage: siteDefault).SendInvitationAsync("new@example.org", "t", chosen, false); + + _sender.Sent.Single().Subject.Should().StartWith(subjectStart); + } + + [Fact] + public async Task WithoutAHost_NothingIsSent_AndItReportsDisabled() + { + var result = await Service(smtpHost: "").SendInvitationAsync("new@example.org", "t", null, false); + + result.Should().Be(MailSendResult.Fail(MailSendResult.Disabled)); + _sender.Sent.Should().BeEmpty(); + Service(smtpHost: "").IsEnabled.Should().BeFalse(); + } + + [Fact] + public async Task ASenderFailure_IsPassedOnAsAValue() + { + _sender.Result = MailSendResult.Fail(MailSendResult.Timeout); + + (await Service().SendInvitationAsync("new@example.org", "t", null, false)).Should().Be(MailSendResult.Fail(MailSendResult.Timeout)); + } + + [Fact] + public async Task AnExceptionAnywhere_NeverEscapes() + { + _sender.Throw = true; + + var result = await Service().SendInvitationAsync("new@example.org", "t", null, false); + + result.Should().Be(MailSendResult.Fail(MailSendResult.Unknown)); + } + + [Fact] + public async Task ARecipientWithoutAnAddress_IsRefused() + { + var result = await Service().SendAccountDeactivatedAsync(new ApplicationUser { Email = null }); + + result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected)); + _sender.Sent.Should().BeEmpty(); + } + + [Fact] + public async Task Deactivation_IsAddressedToTheUser_InTheirLanguage_WithoutALink() + { + var user = new ApplicationUser { Email = "user@example.org", DisplayName = "Jan", PreferredLanguage = "en" }; + + await Service().SendAccountDeactivatedAsync(user); + + var mail = _sender.Sent.Single(); + mail.Subject.Should().Contain("deactivated"); + mail.TextBody.Should().Contain("Hello Jan,").And.NotContain("https://"); + } + + [Fact] + public async Task Reactivation_LinksToTheLoginPage() + { + await Service().SendAccountReactivatedAsync(new ApplicationUser { Email = "user@example.org", DisplayName = "Jan" }); + + _sender.Sent.Single().HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/login"); + } + + [Fact] + public async Task RoleChange_NamesTheNewRole_InTheUsersLanguage() + { + await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "nl" }, "Administrator"); + await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "en" }, "Administrator"); + + _sender.Sent[0].TextBody.Should().Contain("Beheerder"); + _sender.Sent[1].TextBody.Should().Contain("Administrator"); + } + + [Fact] + public async Task AnAbsoluteLogoUrl_IsUsedAsIs_AndNoLogoMeansTheSiteName() + { + await Service(logo: "https://cdn.example.org/logo.png").SendInvitationAsync("a@example.org", "t", null, false); + await Service(logo: "").SendInvitationAsync("a@example.org", "t", null, false); + + _sender.Sent[0].HtmlBody.Should().Contain("https://cdn.example.org/logo.png"); + _sender.Sent[1].HtmlBody.Should().NotContain(" + IdentityMailService.BuildLink(baseUrl, path).Should().Be(expected); +} diff --git a/src/SlpModularCms.Core.Tests/Email/MigrationRoundTripTests.cs b/src/SlpModularCms.Core.Tests/Email/MigrationRoundTripTests.cs index b1fdb31..221639d 100644 --- a/src/SlpModularCms.Core.Tests/Email/MigrationRoundTripTests.cs +++ b/src/SlpModularCms.Core.Tests/Email/MigrationRoundTripTests.cs @@ -32,15 +32,26 @@ public class MigrationRoundTripTests await db.Database.EnsureDeletedAsync(); await db.Database.MigrateAsync(); (await TableExists(db, "SiteSettings")).Should().BeTrue(); + (await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeTrue(); + (await ColumnExists(db, "Invitations", "Language")).Should().BeTrue(); var migrations = db.GetService().Migrations.Keys.OrderBy(k => k).ToList(); var previous = migrations[^2]; var migrator = db.GetService(); await migrator.MigrateAsync(previous); // undo the newest - (await TableExists(db, "SiteSettings")).Should().BeFalse(); + (await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeFalse(); + (await ColumnExists(db, "Invitations", "Language")).Should().BeFalse(); + (await TableExists(db, "SiteSettings")).Should().BeTrue(); // the one before stays await migrator.MigrateAsync(); // and apply it again + (await ColumnExists(db, "Users", "PreferredLanguage")).Should().BeTrue(); + (await ColumnExists(db, "Invitations", "Language")).Should().BeTrue(); + + // The one before that can be undone as well (down to the schema without any of this feature). + await migrator.MigrateAsync(migrations[^3]); + (await TableExists(db, "SiteSettings")).Should().BeFalse(); + await migrator.MigrateAsync(); (await TableExists(db, "SiteSettings")).Should().BeTrue(); } finally @@ -49,6 +60,14 @@ public class MigrationRoundTripTests } } + private static async Task ColumnExists(ApplicationDbContext db, string table, string column) + { + var rows = await db.Database + .SqlQuery($"select count(*) as Value from information_schema.columns where table_schema = database() and table_name = {table} and column_name = {column}") + .ToListAsync(); + return rows[0] > 0; + } + private static async Task TableExists(ApplicationDbContext db, string table) { var rows = await db.Database diff --git a/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs b/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs index 5af01d2..a1fb5f7 100644 --- a/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs +++ b/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs @@ -79,7 +79,7 @@ public class DeactivatedUserAccessTests : IAsyncLifetime { using var scope = _host.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive }; + var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive, SecurityStamp = "stamp-1" }; db.Users.Add(user); await db.SaveChangesAsync(); return user; @@ -102,16 +102,17 @@ public class DeactivatedUserAccessTests : IAsyncLifetime await db.SaveChangesAsync(); } - private static string TokenFor(Guid userId) + private static string TokenFor(Guid userId, string? stamp = "stamp-1") { var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Jwt.Secret)); var token = new JwtSecurityToken( Jwt.Issuer, Jwt.Audience, - [ + new[] + { new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()), new Claim(ClaimTypes.Role, "Owner") - ], + }.Concat(stamp is null ? [] : [new Claim(ActiveUserTokenValidation.StampClaim, stamp)]), expires: DateTime.UtcNow.AddMinutes(30), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); return new JwtSecurityTokenHandler().WriteToken(token); @@ -181,4 +182,44 @@ public class DeactivatedUserAccessTests : IAsyncLifetime (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); } + + private async Task SetStampAsync(Guid id, string stamp) + { + using var scope = _host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.SingleAsync(u => u.Id == id); + user.SecurityStamp = stamp; + await db.SaveChangesAsync(); + } + + [Fact] + public async Task APasswordChange_EndsTheAccessTokensIssuedBefore_ForGetAndPost() + { + var user = await AddUserAsync(); + var token = TokenFor(user.Id, "stamp-1"); + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK); + + await SetStampAsync(user.Id, "stamp-2"); // what a password change or reset does + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); + (await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.Unauthorized); + // A token issued after the change carries the new stamp and works. + (await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "stamp-2"))).Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task ATokenWithoutAStamp_IssuedBeforeThisCheckExisted_IsRefused() + { + var user = await AddUserAsync(); + + (await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, stamp: null))).Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task ATokenWithAWrongStamp_IsRefused() + { + var user = await AddUserAsync(); + + (await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "someone-elses-stamp"))).Should().Be(HttpStatusCode.Unauthorized); + } } diff --git a/src/SlpModularCms.Core.Tests/Identity/InvitationServiceTests.cs b/src/SlpModularCms.Core.Tests/Identity/InvitationServiceTests.cs index c62bb87..10cf1af 100644 --- a/src/SlpModularCms.Core.Tests/Identity/InvitationServiceTests.cs +++ b/src/SlpModularCms.Core.Tests/Identity/InvitationServiceTests.cs @@ -394,4 +394,32 @@ public class InvitationServiceTests (await _service.RegenerateInvitationAsync(inv.Id)).Should().BeNull(); } + + [Fact] + public async Task CreateInvitationAsync_StoresTheNormalisedLanguage() + { + var token = await _service.CreateInvitationAsync("lang@example.com", "User", "EN-gb"); + + (await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().Be("en"); + (await _service.GetAllPendingInvitationsAsync()).Single().Language.Should().Be("en"); + } + + [Fact] + public async Task CreateInvitationAsync_IgnoresAnUnsupportedLanguage() + { + var token = await _service.CreateInvitationAsync("lang2@example.com", "User", "de"); + + (await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().BeNull(); + } + + [Fact] + public async Task CompleteInvitationAsync_CopiesTheInvitationLanguageToTheNewAccount() + { + var token = await _service.CreateInvitationAsync("lang3@example.com", "User", "en"); + _userManager.CreateAsync(Arg.Any(), Arg.Any()).Returns(IdentityResult.Success); + + await _service.CompleteInvitationAsync(token, "SafePassword123!", "Naam"); + + await _userManager.Received(1).CreateAsync(Arg.Is(u => u.PreferredLanguage == "en"), "SafePassword123!"); + } } diff --git a/src/SlpModularCms.Core.Tests/Identity/SessionEndsOnPasswordChangeTests.cs b/src/SlpModularCms.Core.Tests/Identity/SessionEndsOnPasswordChangeTests.cs new file mode 100644 index 0000000..704ff44 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Identity/SessionEndsOnPasswordChangeTests.cs @@ -0,0 +1,122 @@ +using System.Net; +using FluentAssertions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Data; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Identity.Authorization; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.Identity.Services; + +namespace SlpModularCms.Core.Tests.Identity; + +/// +/// The real chain end to end (real Identity password handling, real tokens from , +/// the real bearer check): a password change ends the access tokens issued before it, and the refresh +/// token then silently gives a new one that works. +/// +public class SessionEndsOnPasswordChangeTests : IAsyncLifetime +{ + private static readonly JwtSettings Jwt = new() + { + Secret = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789", + Issuer = "test-issuer", + Audience = "test-audience", + ExpiryMinutes = 30 + }; + + private readonly string _dbName = Guid.NewGuid().ToString(); + private IHost _host = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + _host = await new HostBuilder().ConfigureWebHost(web => + { + web.UseTestServer(); + web.ConfigureServices(services => + { + services.AddLogging(); + services.AddRouting(); + services.AddDbContext(o => o.UseInMemoryDatabase(_dbName)); + services.AddIdentityCore().AddRoles().AddEntityFrameworkStores(); + services.Configure(o => + { + o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes; + }); + services.AddScoped(); + services.AddAuthentication("Bearer").AddJwtBearer(o => o.UseCmsTokenValidation(JwtTokenValidation.Create(Jwt))); + services.AddAuthorization(); + }); + web.Configure(app => + { + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(e => e.MapGet("/data", () => Results.Ok("secret")).RequireAuthorization()); + }); + }).StartAsync(); + _client = _host.GetTestClient(); + + using var scope = _host.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var result = await users.CreateAsync( + new ApplicationUser { UserName = "owner@test.nl", Email = "owner@test.nl", IsActive = true, PreferredLanguage = "en" }, "Password1!"); + result.Succeeded.Should().BeTrue(string.Join(",", result.Errors.Select(e => e.Code))); + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _host.StopAsync(); + _host.Dispose(); + } + + private async Task GetAsync(string token) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/data"); + request.Headers.Authorization = new("Bearer", token); + return (await _client.SendAsync(request)).StatusCode; + } + + private async Task InScope(Func> action) + { + using var scope = _host.Services.CreateScope(); + return await action(scope.ServiceProvider.GetRequiredService()); + } + + [Fact] + public async Task ARealLoginToken_Works_AndCarriesTheUsersLanguage() + { + var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!")); + + (await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK); + login.User.Language.Should().Be("en"); + } + + [Fact] + public async Task APasswordChange_EndsTheEarlierAccessToken_AndTheRefreshTokenGivesAWorkingNewOne() + { + var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!")); + (await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK); + + await InScope(async a => + { + await a.ChangePasswordAsync(login.User.Id, "Password1!", "Another-Pass2!"); + return 0; + }); + + (await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.Unauthorized); + + var refreshed = await InScope(a => a.RefreshTokenAsync(login.RefreshToken)); + (await GetAsync(refreshed.AccessToken)).Should().Be(HttpStatusCode.OK); + } +} diff --git a/src/SlpModularCms.Core/Data/ApplicationDbContext.cs b/src/SlpModularCms.Core/Data/ApplicationDbContext.cs index a72fdbd..80531fe 100644 --- a/src/SlpModularCms.Core/Data/ApplicationDbContext.cs +++ b/src/SlpModularCms.Core/Data/ApplicationDbContext.cs @@ -39,7 +39,11 @@ public class ApplicationDbContext : IdentityDbContext(entity => { entity.ToTable("Users"); }); + builder.Entity(entity => + { + entity.ToTable("Users"); + entity.Property(e => e.PreferredLanguage).HasMaxLength(8); + }); builder.Entity(entity => { entity.ToTable("Roles"); }); builder.Entity>(entity => { entity.ToTable("UserRoles"); }); builder.Entity>(entity => { entity.ToTable("UserClaims"); }); @@ -74,6 +78,7 @@ public class ApplicationDbContext : IdentityDbContext e.Token).IsUnique(); entity.Property(e => e.Token).IsRequired().HasMaxLength(256); entity.Property(e => e.Email).IsRequired().HasMaxLength(256); + entity.Property(e => e.Language).HasMaxLength(8); }); // Configuratie voor SiteSettings (een rij, Id = 1) diff --git a/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs index 78f2d5c..2a4c7df 100644 --- a/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs @@ -28,6 +28,7 @@ public static class EmailServiceCollectionExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddScoped(); + services.TryAddScoped(); return services; } diff --git a/src/SlpModularCms.Core/Email/IdentityMailService.cs b/src/SlpModularCms.Core/Email/IdentityMailService.cs new file mode 100644 index 0000000..cac782d --- /dev/null +++ b/src/SlpModularCms.Core/Email/IdentityMailService.cs @@ -0,0 +1,105 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.SiteSettings; + +namespace SlpModularCms.Core.Email; + +/// +/// Builds and sends the identity mails (invitation, new link, notices). One orchestration point so a +/// controller never knows about templates, languages, links or the sender. +/// +public interface IIdentityMailService +{ + /// True when this site can send mail (an SMTP host is configured). + bool IsEnabled { get; } + + Task SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default); + Task SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default); + Task SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default); + Task SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default); +} + +public sealed class IdentityMailService( + IEmailSender sender, + IMailTemplateRenderer renderer, + ILanguageResolver languages, + ISiteSettingsService siteSettings, + IOptions email, + IOptions app, + IOptions invitation, + ILogger logger) : IIdentityMailService +{ + public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host); + + public Task SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default) => + SendAsync( + isNewLink ? MailKind.NewInvitationLink : MailKind.Invitation, + email, + language, + recipientName: null, + actionPath: "/invite/complete?token=" + Uri.EscapeDataString(token), + validForMinutes: invitation.Value.ExpiryHours * 60, + detail: null, + ct); + + public Task SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default) => + SendAsync(MailKind.AccountDeactivated, user.Email, user.PreferredLanguage, user.DisplayName, null, null, null, ct); + + public Task SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default) => + SendAsync(MailKind.AccountReactivated, user.Email, user.PreferredLanguage, user.DisplayName, "/login", null, null, ct); + + public Task SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default) => + SendAsync(MailKind.RoleChanged, user.Email, user.PreferredLanguage, user.DisplayName, null, null, newRole, ct); + + private async Task SendAsync( + MailKind kind, string? to, string? language, string? recipientName, string? actionPath, + int? validForMinutes, string? detail, CancellationToken ct) + { + if (!IsEnabled) return MailSendResult.Fail(MailSendResult.Disabled); + + try + { + if (string.IsNullOrWhiteSpace(to)) return MailSendResult.Fail(MailSendResult.Rejected); + + var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(ct); + var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/'); + var model = new MailModel( + SiteName: fromName, + RecipientName: recipientName, + ActionUrl: actionPath is null ? null : BuildLink(baseUrl, actionPath), + ValidForMinutes: validForMinutes, + Detail: detail, + LogoUrl: ResolveLogo(baseUrl, email.Value.LogoUrl), + BrandColor: string.IsNullOrWhiteSpace(email.Value.BrandColor) ? null : email.Value.BrandColor); + + var rendered = renderer.Render(kind, languages.Resolve(language), model); + var result = await sender.SendAsync( + new OutgoingMail(to, rendered.Subject, rendered.Html, rendered.Text, fromAddress, fromName), ct); + + // Recipient DOMAIN only: never the address, the link or the token. + var domain = to.Contains('@') ? to[(to.LastIndexOf('@') + 1)..] : "?"; + if (result.Sent) + logger.LogInformation("identity_mail_sent kind={Kind} recipient_domain={Domain}", kind, domain); + else + logger.LogWarning("identity_mail_failed kind={Kind} recipient_domain={Domain} code={Code}", kind, domain, result.ErrorCode); + return result; + } + catch (Exception ex) + { + logger.LogWarning("identity_mail_failed kind={Kind} code={Code} exception={ExceptionType}", kind, MailSendResult.Unknown, ex.GetType().Name); + return MailSendResult.Fail(MailSendResult.Unknown); + } + } + + /// Public site address + the admin base path + the app path (the admin is mounted under /admin). + public static string BuildLink(string publicBaseUrl, string appPath) => + publicBaseUrl.TrimEnd('/') + "/admin" + (appPath.StartsWith('/') ? appPath : "/" + appPath); + + private static string? ResolveLogo(string baseUrl, string? logoUrl) + { + if (string.IsNullOrWhiteSpace(logoUrl)) return null; + return logoUrl.StartsWith('/') ? baseUrl + logoUrl : logoUrl; + } +} diff --git a/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs b/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs index 6fb900b..9185a00 100644 --- a/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs +++ b/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs @@ -19,6 +19,9 @@ namespace SlpModularCms.Core.Identity.Authorization; /// public static class ActiveUserTokenValidation { + /// Claim carrying the user's security stamp at the moment the access token was issued. + public const string StampClaim = "stamp"; + /// /// The one place the bearer scheme is configured: signature/lifetime parameters plus the /// active-account check. Hosts and tests both go through this, so the check cannot be dropped @@ -46,16 +49,26 @@ public static class ActiveUserTokenValidation } var db = context.HttpContext.RequestServices.GetRequiredService(); - var isActive = await db.Users + var user = await db.Users .AsNoTracking() .Where(u => u.Id == userId) - .Select(u => (bool?)u.IsActive) + .Select(u => new { u.IsActive, u.SecurityStamp }) .FirstOrDefaultAsync(context.HttpContext.RequestAborted); - if (isActive != true) + if (user is null || !user.IsActive) { // Same 401 whether the user is gone or deactivated: which one is not the caller's business. context.Fail("Account is not active."); + return; + } + + // A password change or reset changes the stamp, which ends every access token issued before it. + // A token without the claim (issued before this check existed) is refused once; the refresh + // token then silently issues a new one that carries it. + var tokenStamp = principal?.FindFirstValue(StampClaim); + if (tokenStamp is null || !string.Equals(tokenStamp, user.SecurityStamp ?? string.Empty, StringComparison.Ordinal)) + { + context.Fail("Session is no longer valid."); } } } diff --git a/src/SlpModularCms.Core/Identity/Entities/ApplicationUser.cs b/src/SlpModularCms.Core/Identity/Entities/ApplicationUser.cs index c01f43f..40e99b6 100644 --- a/src/SlpModularCms.Core/Identity/Entities/ApplicationUser.cs +++ b/src/SlpModularCms.Core/Identity/Entities/ApplicationUser.cs @@ -24,6 +24,11 @@ public class ApplicationUser : IdentityUser /// public string? DisplayName { get; set; } + /// + /// Voorkeurstaal van de gebruiker (nl of en), ook voor e-mails. Null = standaardtaal van de site. + /// + public string? PreferredLanguage { get; set; } + /// /// Navigatie-eigenschap naar module-specifieke rechten. /// diff --git a/src/SlpModularCms.Core/Identity/Entities/Invitation.cs b/src/SlpModularCms.Core/Identity/Entities/Invitation.cs index bd74d96..83d923d 100644 --- a/src/SlpModularCms.Core/Identity/Entities/Invitation.cs +++ b/src/SlpModularCms.Core/Identity/Entities/Invitation.cs @@ -12,6 +12,10 @@ public class Invitation public string Email { get; set; } = string.Empty; public string Role { get; set; } = string.Empty; public string Token { get; set; } = string.Empty; + + /// Taal van de uitnodigingsmail en voorkeurstaal van het nieuwe account (nl of en); null = sitestandaard. + public string? Language { get; set; } + public DateTimeOffset ExpiryDate { get; set; } public bool IsAccepted { get; set; } public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; diff --git a/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs b/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs index 79971b7..80760e7 100644 --- a/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs +++ b/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs @@ -4,13 +4,13 @@ namespace SlpModularCms.Core.Identity.Models; [ExcludeFromCodeCoverage] public record CreateOwnerRequest(string Name, string Email, string Password); [ExcludeFromCodeCoverage] public record LoginRequest(string Email, string Password); -[ExcludeFromCodeCoverage] public record InviteUserRequest(string Email, string Role); +[ExcludeFromCodeCoverage] public record InviteUserRequest(string Email, string Role, string? Language = null); [ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null); [ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole); -[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email); +[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email, string? Language = null); [ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword); [ExcludeFromCodeCoverage] public record SetUserActiveRequest(bool IsActive); -[ExcludeFromCodeCoverage] public record PendingInvitationInfo(Guid Id, string Email, string Role, string Token, DateTimeOffset CreatedAt, bool IsExpired = false); +[ExcludeFromCodeCoverage] public record PendingInvitationInfo(Guid Id, string Email, string Role, string Token, DateTimeOffset CreatedAt, bool IsExpired = false, string? Language = null); [ExcludeFromCodeCoverage] public record UserDto( Guid Id, @@ -21,4 +21,5 @@ public record UserDto( DateTimeOffset CreatedAt, bool InvitationPending, string? InviteLink, - bool InvitationExpired = false); + bool InvitationExpired = false, + string? Language = null); diff --git a/src/SlpModularCms.Core/Identity/Models/TokenResponse.cs b/src/SlpModularCms.Core/Identity/Models/TokenResponse.cs index 0ea2453..9590ff8 100644 --- a/src/SlpModularCms.Core/Identity/Models/TokenResponse.cs +++ b/src/SlpModularCms.Core/Identity/Models/TokenResponse.cs @@ -23,5 +23,6 @@ public record UserResponse( string Email, string Name, string Role, - bool IsActive + bool IsActive, + string? Language = null ); diff --git a/src/SlpModularCms.Core/Identity/Services/AuthService.cs b/src/SlpModularCms.Core/Identity/Services/AuthService.cs index 93f8782..03670da 100644 --- a/src/SlpModularCms.Core/Identity/Services/AuthService.cs +++ b/src/SlpModularCms.Core/Identity/Services/AuthService.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using SlpModularCms.Core.Data; using SlpModularCms.Core.Exceptions; +using SlpModularCms.Core.Identity.Authorization; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Observability; @@ -117,7 +118,10 @@ public class AuthService : IAuthService { new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new(JwtRegisteredClaimNames.Email, user.Email!), - new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) + new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + // The security stamp changes on a password change/reset. The access-token check compares it, so + // such a change ends every access token issued before it (see ActiveUserTokenValidation). + new(ActiveUserTokenValidation.StampClaim, user.SecurityStamp ?? string.Empty) }; foreach (var role in roles) @@ -155,7 +159,8 @@ public class AuthService : IAuthService Email: user.Email!, Name: user.DisplayName ?? user.Email!, Role: primaryRole, - IsActive: user.IsActive + IsActive: user.IsActive, + Language: user.PreferredLanguage ); return new TokenResponse(accessToken, refreshToken, expiry, userResponse); diff --git a/src/SlpModularCms.Core/Identity/Services/IInvitationService.cs b/src/SlpModularCms.Core/Identity/Services/IInvitationService.cs index 8dcdc5b..ebc4f49 100644 --- a/src/SlpModularCms.Core/Identity/Services/IInvitationService.cs +++ b/src/SlpModularCms.Core/Identity/Services/IInvitationService.cs @@ -10,7 +10,7 @@ public interface IInvitationService /// /// Maakt een nieuwe uitnodiging aan en retourneert het token. /// - Task CreateInvitationAsync(string email, string role); + Task CreateInvitationAsync(string email, string role, string? language = null); /// /// Valideert of een uitnodigings-token nog geldig is. diff --git a/src/SlpModularCms.Core/Identity/Services/InvitationService.cs b/src/SlpModularCms.Core/Identity/Services/InvitationService.cs index 33fff9e..8f2d07b 100644 --- a/src/SlpModularCms.Core/Identity/Services/InvitationService.cs +++ b/src/SlpModularCms.Core/Identity/Services/InvitationService.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using SlpModularCms.Core.Data; +using SlpModularCms.Core.Email; using SlpModularCms.Core.Exceptions; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; @@ -25,7 +26,7 @@ public class InvitationService : IInvitationService _settings = settings.Value; } - public async Task CreateInvitationAsync(string email, string role) + public async Task CreateInvitationAsync(string email, string role, string? language = null) { var user = await _userManager.FindByEmailAsync(email); if (user != null) @@ -57,6 +58,7 @@ public class InvitationService : IInvitationService { Email = email, Role = role, + Language = MailLanguages.Normalize(language), Token = token, ExpiryDate = DateTimeOffset.UtcNow.AddHours(_settings.ExpiryHours), IsAccepted = false @@ -87,6 +89,7 @@ public class InvitationService : IInvitationService UserName = invitation.Email, Email = invitation.Email, DisplayName = string.IsNullOrWhiteSpace(name) ? null : name.Trim(), + PreferredLanguage = invitation.Language, IsActive = true }; @@ -131,7 +134,7 @@ public class InvitationService : IInvitationService // Expired ones are included on purpose: dropping them made an invited person who did not // activate in time vanish from the list, so the administrator could neither see nor remove them. return invitations - .Select(i => new PendingInvitationInfo(i.Id, i.Email, i.Role, i.Token, i.CreatedAt, i.IsExpired)) + .Select(i => new PendingInvitationInfo(i.Id, i.Email, i.Role, i.Token, i.CreatedAt, i.IsExpired, i.Language)) .ToList(); } diff --git a/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.Designer.cs b/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.Designer.cs new file mode 100644 index 0000000..db45041 --- /dev/null +++ b/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.Designer.cs @@ -0,0 +1,474 @@ +// +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("20261108180809_AddLanguagePreference")] + partial class AddLanguagePreference + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + b.Property("FriendlyName") + .HasColumnType("longtext"); + + b.Property("Xml") + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("RoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .HasColumnType("char(36)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("UserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("char(36)"); + + b.Property("RoleId") + .HasColumnType("char(36)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("char(36)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("UserTokens", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("DisplayName") + .HasColumnType("longtext"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("PreferredLanguage") + .HasMaxLength(8) + .HasColumnType("varchar(8)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("LastUpdatedAt") + .HasColumnType("datetime"); + + b.Property("Message") + .HasColumnType("longtext"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("UpdatedBy") + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.ToTable("AvailabilityState", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ExpiryDate") + .HasColumnType("datetime"); + + b.Property("IsAccepted") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(8) + .HasColumnType("varchar(8)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("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("UserId") + .HasColumnType("char(36)"); + + b.Property("ModuleName") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Permission") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("UserId", "ModuleName", "Permission"); + + b.ToTable("ModulePermissions"); + }); + + modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByIp") + .HasColumnType("longtext"); + + b.Property("ExpiryDate") + .HasColumnType("datetime"); + + b.Property("IsRevoked") + .HasColumnType("tinyint(1)"); + + b.Property("IsUsed") + .HasColumnType("tinyint(1)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("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("Id") + .HasColumnType("int"); + + b.Property("MailFromAddress") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("MailFromName") + .HasMaxLength(80) + .HasColumnType("varchar(80)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.Property("UpdatedBy") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.ToTable("SiteSettings", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", 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", 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 + } + } +} diff --git a/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.cs b/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.cs new file mode 100644 index 0000000..2ccca9b --- /dev/null +++ b/src/SlpModularCms.Core/Migrations/20261108180809_AddLanguagePreference.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Core.Migrations +{ + /// + public partial class AddLanguagePreference : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "PreferredLanguage", + table: "Users", + type: "varchar(8)", + maxLength: 8, + nullable: true); + + migrationBuilder.AddColumn( + name: "Language", + table: "Invitations", + type: "varchar(8)", + maxLength: 8, + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "PreferredLanguage", + table: "Users"); + + migrationBuilder.DropColumn( + name: "Language", + table: "Invitations"); + } + } +} diff --git a/src/SlpModularCms.Core/Migrations/ApplicationDbContextModelSnapshot.cs b/src/SlpModularCms.Core/Migrations/ApplicationDbContextModelSnapshot.cs index f70c748..d518bf4 100644 --- a/src/SlpModularCms.Core/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Core/Migrations/ApplicationDbContextModelSnapshot.cs @@ -214,6 +214,10 @@ namespace SlpModularCms.Core.Migrations b.Property("PhoneNumberConfirmed") .HasColumnType("tinyint(1)"); + b.Property("PreferredLanguage") + .HasMaxLength(8) + .HasColumnType("varchar(8)"); + b.Property("SecurityStamp") .HasColumnType("longtext"); @@ -279,6 +283,10 @@ namespace SlpModularCms.Core.Migrations b.Property("IsAccepted") .HasColumnType("tinyint(1)"); + b.Property("Language") + .HasMaxLength(8) + .HasColumnType("varchar(8)"); + b.Property("Role") .IsRequired() .HasColumnType("longtext"); diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerMailTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerMailTests.cs new file mode 100644 index 0000000..77b97ef --- /dev/null +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerMailTests.cs @@ -0,0 +1,334 @@ +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using SlpModularCms.Core.Data; +using SlpModularCms.Core.Email; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.Identity.Services; +using SlpModularCms.Modules.Identity.Controllers; + +namespace SlpModularCms.Modules.Identity.Tests.Controllers; + +/// +/// What the mail adds to the user-management actions: the invitation mail with the chosen language, the +/// resend, the notices, the language preference. A mail failure never fails the action. +/// +public class UsersControllerMailTests : IDisposable +{ + private readonly ApplicationDbContext _context; + private readonly UserManager _userManager; + private readonly RoleManager _roleManager; + private readonly IInvitationService _invitations = Substitute.For(); + private readonly IIdentityMailService _mail = Substitute.For(); + + public UsersControllerMailTests() + { + _context = new ApplicationDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); + _userManager = new UserManager( + new UserStore(_context), + Options.Create(new IdentityOptions()), new PasswordHasher(), + Array.Empty>(), Array.Empty>(), + new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), null!, + NullLogger>.Instance); + _roleManager = new RoleManager( + new RoleStore(_context), + Array.Empty>(), new UpperInvariantLookupNormalizer(), + new IdentityErrorDescriber(), NullLogger>.Instance); + + _invitations.GetAllPendingInvitationsAsync().Returns(new List()); + _mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Ok); + _mail.SendAccountDeactivatedAsync(default!, default).ReturnsForAnyArgs(MailSendResult.Ok); + _mail.SendAccountReactivatedAsync(default!, default).ReturnsForAnyArgs(MailSendResult.Ok); + _mail.SendRoleChangedAsync(default!, default!, default).ReturnsForAnyArgs(MailSendResult.Ok); + } + + public void Dispose() + { + _userManager.Dispose(); + _roleManager.Dispose(); + _context.Dispose(); + } + + private async Task Add(string email, string role, string? language = null, bool active = true) + { + if (!await _roleManager.RoleExistsAsync(role)) await _roleManager.CreateAsync(new ApplicationRole { Name = role }); + var user = new ApplicationUser + { + Id = Guid.NewGuid(), Email = email, UserName = email, NormalizedEmail = email.ToUpperInvariant(), + NormalizedUserName = email.ToUpperInvariant(), DisplayName = "Naam " + email, IsActive = active, + PreferredLanguage = language, CreatedAt = DateTimeOffset.UtcNow + }; + await _userManager.CreateAsync(user, "Password1!"); + await _userManager.AddToRoleAsync(user, role); + return user; + } + + private UsersController As(ApplicationUser caller) + { + var controller = new UsersController(_invitations, _userManager, _mail); + controller.ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.Name, caller.UserName!), new Claim(ClaimTypes.NameIdentifier, caller.Id.ToString())], "Test")) + } + }; + return controller; + } + + private void Pending(Guid id, string role = "User", bool expired = false, string? language = "en") => + _invitations.GetAllPendingInvitationsAsync().Returns(new List + { + new(id, "invited@test.com", role, "old-token", DateTimeOffset.UtcNow.AddDays(-2), expired, language) + }); + + private static T Prop(object? body, string name) => + (T)body!.GetType().GetProperty(name)!.GetValue(body)!; + + // --- invite --- + + [Fact] + public async Task Invite_CreatesTheInvitationWithTheChosenLanguage_SendsTheMail_AndReturnsLinkAndResult() + { + var owner = await Add("owner@test.com", "Owner"); + _invitations.CreateInvitationAsync("new@test.com", "User", "en").Returns("tok"); + + var result = await As(owner).Invite(new InviteUserRequest("new@test.com", "User", "en")); + + var body = result.Should().BeOfType().Subject.Value; + Prop(body, "inviteLink").Should().Be("/invite/complete?token=tok"); + var mail = Prop(body, "mail"); + Prop(mail, "sent").Should().BeTrue(); + await _mail.Received(1).SendInvitationAsync("new@test.com", "tok", "en", false, Arg.Any()); + } + + [Fact] + public async Task Invite_WhenTheMailFails_StillSucceeds_AndReportsTheFailureNextToTheLink() + { + var owner = await Add("owner@test.com", "Owner"); + _invitations.CreateInvitationAsync("new@test.com", "User", null).Returns("tok"); + _mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.Timeout)); + + var result = await As(owner).Invite(new InviteUserRequest("new@test.com", "User")); + + var body = result.Should().BeOfType().Subject.Value; + Prop(body, "inviteLink").Should().NotBeNullOrEmpty(); + var mail = Prop(body, "mail"); + Prop(mail, "sent").Should().BeFalse(); + Prop(mail, "error").Should().Be("timeout"); + } + + [Fact] + public async Task Invite_OnASiteWithoutMail_HasNoMailResult() + { + var owner = await Add("owner@test.com", "Owner"); + _invitations.CreateInvitationAsync("new@test.com", "User", null).Returns("tok"); + _mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.Disabled)); + + var result = await As(owner).Invite(new InviteUserRequest("new@test.com", "User")); + + Prop(result.Should().BeOfType().Subject.Value, "mail").Should().BeNull(); + } + + [Fact] + public async Task Invite_RejectsAnUnsupportedLanguage_WithoutCreatingAnything() + { + var owner = await Add("owner@test.com", "Owner"); + + var result = await As(owner).Invite(new InviteUserRequest("new@test.com", "User", "de")); + + result.Should().BeOfType(); + await _invitations.DidNotReceiveWithAnyArgs().CreateInvitationAsync(default!, default!, default); + } + + // --- regenerate / resend --- + + [Fact] + public async Task Regenerate_SendsTheNewLinkMail_InTheLanguageOfTheInvitation() + { + var owner = await Add("owner@test.com", "Owner"); + var id = Guid.NewGuid(); + Pending(id, language: "en"); + _invitations.RegenerateInvitationAsync(id).Returns("new-token"); + + var result = await As(owner).RegenerateInvite(id); + + Prop(result.Should().BeOfType().Subject.Value, "inviteLink").Should().Contain("new-token"); + await _mail.Received(1).SendInvitationAsync("invited@test.com", "new-token", "en", true, Arg.Any()); + } + + [Fact] + public async Task Resend_OfAValidInvitation_SendsTheExistingLink_WithoutCreatingANewOne() + { + var owner = await Add("owner@test.com", "Owner"); + var id = Guid.NewGuid(); + Pending(id, expired: false); + + var result = await As(owner).ResendInvite(id); + + Prop(result.Should().BeOfType().Subject.Value, "inviteLink").Should().Contain("old-token"); + await _invitations.DidNotReceive().RegenerateInvitationAsync(Arg.Any()); + await _mail.Received(1).SendInvitationAsync("invited@test.com", "old-token", "en", false, Arg.Any()); + } + + [Fact] + public async Task Resend_OfAnExpiredInvitation_CreatesANewLinkFirst() + { + var owner = await Add("owner@test.com", "Owner"); + var id = Guid.NewGuid(); + Pending(id, expired: true); + _invitations.RegenerateInvitationAsync(id).Returns("fresh"); + + var result = await As(owner).ResendInvite(id); + + Prop(result.Should().BeOfType().Subject.Value, "inviteLink").Should().Contain("fresh"); + await _mail.Received(1).SendInvitationAsync("invited@test.com", "fresh", "en", true, Arg.Any()); + } + + [Fact] + public async Task Resend_ReportsAFailedMail_AndKeepsTheLink() + { + var owner = await Add("owner@test.com", "Owner"); + var id = Guid.NewGuid(); + Pending(id); + _mail.SendInvitationAsync(default!, default!, default, default, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.AuthFailed)); + + var body = (await As(owner).ResendInvite(id)).Should().BeOfType().Subject.Value; + + Prop(Prop(body, "mail"), "error").Should().Be("auth_failed"); + Prop(body, "inviteLink").Should().Contain("old-token"); + } + + [Fact] + public async Task Resend_FollowsTheHierarchy_AndIsNotFoundForUnknownInvitations() + { + var admin = await Add("admin@test.com", "Administrator"); + var id = Guid.NewGuid(); + Pending(id, role: "Administrator"); + + (await As(admin).ResendInvite(id)).Should().BeOfType(); + (await As(admin).ResendInvite(Guid.NewGuid())).Should().BeOfType(); + await _mail.DidNotReceiveWithAnyArgs().SendInvitationAsync(default!, default!, default, default, default); + } + + // --- notices --- + + [Fact] + public async Task Deactivating_SendsANotice_Reactivating_SendsAnother_AndNoChangeSendsNothing() + { + var owner = await Add("owner@test.com", "Owner"); + var user = await Add("user@test.com", "User", language: "en"); + + await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(false)); + await _mail.Received(1).SendAccountDeactivatedAsync(Arg.Is(u => u.Id == user.Id), Arg.Any()); + + await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(false)); // already inactive: no second notice + await _mail.Received(1).SendAccountDeactivatedAsync(Arg.Any(), Arg.Any()); + + await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(true)); + await _mail.Received(1).SendAccountReactivatedAsync(Arg.Is(u => u.Id == user.Id), Arg.Any()); + } + + [Fact] + public async Task ANoticeThatFails_NeverFailsTheAction() + { + var owner = await Add("owner@test.com", "Owner"); + var user = await Add("user@test.com", "User"); + _mail.SendAccountDeactivatedAsync(default!, default).ReturnsForAnyArgs(MailSendResult.Fail(MailSendResult.Timeout)); + + (await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(false))).Should().BeOfType(); + + (await _userManager.FindByIdAsync(user.Id.ToString()))!.IsActive.Should().BeFalse(); + } + + [Fact] + public async Task ChangingARole_SendsANotice_ButSelectingTheSameRoleDoesNot() + { + var owner = await Add("owner@test.com", "Owner"); + await _roleManager.CreateAsync(new ApplicationRole { Name = "Administrator" }); + var user = await Add("user@test.com", "User"); + + await As(owner).ChangeRole(user.Id, new ChangeRoleRequest("Administrator")); + await _mail.Received(1).SendRoleChangedAsync(Arg.Is(u => u.Id == user.Id), "Administrator", Arg.Any()); + + await As(owner).ChangeRole(user.Id, new ChangeRoleRequest("Administrator")); + await _mail.Received(1).SendRoleChangedAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ChangingTheRoleOfAnInvitation_SendsNoNotice() + { + var owner = await Add("owner@test.com", "Owner"); + var id = Guid.NewGuid(); + Pending(id); + _invitations.UpdateInvitationRoleAsync(id, "Administrator").Returns(true); + + (await As(owner).ChangeRole(id, new ChangeRoleRequest("Administrator"))).Should().BeOfType(); + + await _mail.DidNotReceiveWithAnyArgs().SendRoleChangedAsync(default!, default!, default); + } + + // --- language preference --- + + [Theory] + [InlineData("en", "en")] + [InlineData("NL", "nl")] + [InlineData("", null)] + public async Task UpdateProfile_SetsOrClearsTheLanguage(string requested, string? expected) + { + var user = await Add("user@test.com", "User", language: "en"); + + var result = await As(user).UpdateProfile(new UpdateProfileRequest("Naam", "user@test.com", requested)); + + var dto = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + dto.Language.Should().Be(expected); + (await _userManager.FindByIdAsync(user.Id.ToString()))!.PreferredLanguage.Should().Be(expected); + } + + [Fact] + public async Task UpdateProfile_WithoutALanguage_LeavesThePreferenceAlone() + { + var user = await Add("user@test.com", "User", language: "en"); + + await As(user).UpdateProfile(new UpdateProfileRequest("Naam", "user@test.com")); + + (await _userManager.FindByIdAsync(user.Id.ToString()))!.PreferredLanguage.Should().Be("en"); + } + + [Fact] + public async Task UpdateProfile_RejectsAnUnsupportedLanguage_AndChangesNothing() + { + var user = await Add("user@test.com", "User", language: "en"); + + var result = await As(user).UpdateProfile(new UpdateProfileRequest("Andere naam", "user@test.com", "fr")); + + result.Should().BeOfType(); + var reloaded = await _userManager.FindByIdAsync(user.Id.ToString()); + reloaded!.PreferredLanguage.Should().Be("en"); + reloaded.DisplayName.Should().Be("Naam user@test.com"); + } + + [Fact] + public async Task GetUsers_ShowsTheLanguageOfAccountsAndInvitations() + { + var owner = await Add("owner@test.com", "Owner", language: "nl"); + Pending(Guid.NewGuid(), language: "en"); + _invitations.GetPendingInvitationByEmailAsync(Arg.Any()).Returns((false, null)); + + var result = await As(owner).GetUsers(); + + var list = result.Should().BeOfType().Subject.Value.Should().BeAssignableTo>().Subject.ToList(); + list.Single(u => u.Email == "owner@test.com").Language.Should().Be("nl"); + list.Single(u => u.Email == "invited@test.com").Language.Should().Be("en"); + } +} diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerRoleHierarchyTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerRoleHierarchyTests.cs index b5b7586..d965493 100644 --- a/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerRoleHierarchyTests.cs +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerRoleHierarchyTests.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using SlpModularCms.Core.Data; +using SlpModularCms.Core.Email; using SlpModularCms.Core.Identity.Authorization; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; @@ -81,7 +82,7 @@ public class UsersControllerRoleHierarchyTests : IDisposable private UsersController As(ApplicationUser caller) { - var controller = new UsersController(_invitations, _userManager); + var controller = new UsersController(_invitations, _userManager, Substitute.For()); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerTests.cs index 50e46f3..2d730fc 100644 --- a/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerTests.cs +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/UsersControllerTests.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using SlpModularCms.Core.Data; +using SlpModularCms.Core.Email; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Identity.Services; @@ -22,6 +23,7 @@ public class UsersControllerTests : IDisposable private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IInvitationService _invitationService = Substitute.For(); + private readonly IIdentityMailService _mail = Substitute.For(); public UsersControllerTests() { @@ -60,7 +62,7 @@ public class UsersControllerTests : IDisposable private UsersController CreateController(string? callerEmail = null) { - var controller = new UsersController(_invitationService, _userManager); + var controller = new UsersController(_invitationService, _userManager, _mail); var httpContext = new DefaultHttpContext(); if (callerEmail is not null) { @@ -152,7 +154,7 @@ public class UsersControllerTests : IDisposable [Fact] public async Task UpdateProfile_ReturnsUnauthorized_WhenNoNameIdentifierClaim() { - var controller = new UsersController(_invitationService, _userManager); + var controller = new UsersController(_invitationService, _userManager, _mail); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; var result = await controller.UpdateProfile(new UpdateProfileRequest("Name", "email@test.com")); @@ -164,7 +166,7 @@ public class UsersControllerTests : IDisposable public async Task UpdateProfile_ReturnsNotFound_WhenUserDoesNotExist() { var options = Options.Create(new IdentityOptions()); - var controller = new UsersController(_invitationService, _userManager); + var controller = new UsersController(_invitationService, _userManager, _mail); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "Test")); @@ -181,7 +183,7 @@ public class UsersControllerTests : IDisposable var existingUser = await CreateUser("existing@test.com"); var targetUser = await CreateUser("target@test.com"); - var controller = new UsersController(_invitationService, _userManager); + var controller = new UsersController(_invitationService, _userManager, _mail); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, targetUser.Id.ToString())], "Test")); @@ -197,7 +199,7 @@ public class UsersControllerTests : IDisposable { var user = await CreateUser("user@test.com"); - var controller = new UsersController(_invitationService, _userManager); + var controller = new UsersController(_invitationService, _userManager, _mail); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())], "Test")); diff --git a/src/SlpModularCms.Modules.Identity/Controllers/UsersController.cs b/src/SlpModularCms.Modules.Identity/Controllers/UsersController.cs index 5985d9a..c0e7758 100644 --- a/src/SlpModularCms.Modules.Identity/Controllers/UsersController.cs +++ b/src/SlpModularCms.Modules.Identity/Controllers/UsersController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using SlpModularCms.Core.Email; using SlpModularCms.Core.Identity.Authorization; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; @@ -17,11 +18,16 @@ public class UsersController : ControllerBase { private readonly IInvitationService _invitationService; private readonly UserManager _userManager; + private readonly IIdentityMailService _mail; - public UsersController(IInvitationService invitationService, UserManager userManager) + public UsersController( + IInvitationService invitationService, + UserManager userManager, + IIdentityMailService mail) { _invitationService = invitationService; _userManager = userManager; + _mail = mail; } [HttpGet] @@ -53,7 +59,9 @@ public class UsersController : ControllerBase user.IsActive, user.CreatedAt, isPending, - inviteLink)); + inviteLink, + false, + user.PreferredLanguage)); } // Include pending invitations that have no user account yet @@ -71,7 +79,8 @@ public class UsersController : ControllerBase inv.CreatedAt, true, inv.IsExpired ? null : $"/invite/complete?token={Uri.EscapeDataString(inv.Token)}", - inv.IsExpired)); + inv.IsExpired, + inv.Language)); } } @@ -99,6 +108,18 @@ public class UsersController : ControllerBase return BadRequest(new { detail = "Email is already in use." }); } + // null = leave the preference alone (older clients); "" = clear it (use the site default); + // otherwise nl or en. + if (request.Language is not null) + { + if (request.Language.Length == 0) + user.PreferredLanguage = null; + else if (MailLanguages.Normalize(request.Language) is { } language) + user.PreferredLanguage = language; + else + return BadRequest(new { detail = "Unsupported language." }); + } + user.DisplayName = request.Name; user.Email = request.Email; user.UserName = request.Email; @@ -120,7 +141,9 @@ public class UsersController : ControllerBase user.IsActive, user.CreatedAt, false, - null)); + null, + false, + user.PreferredLanguage)); } [HttpPost("invite")] @@ -130,9 +153,15 @@ public class UsersController : ControllerBase if (!UserManagementRules.CanAssign(requesterRole, request.Role)) return Forbid(); - var token = await _invitationService.CreateInvitationAsync(request.Email, request.Role); + if (!string.IsNullOrEmpty(request.Language) && !MailLanguages.IsSupported(request.Language)) + return BadRequest(new { detail = "Unsupported language." }); + + var token = await _invitationService.CreateInvitationAsync(request.Email, request.Role, request.Language); var inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}"; - return Ok(new { inviteLink }); + + // The invitation exists whatever happens to the mail; the result and the copyable link both go back. + var mail = await _mail.SendInvitationAsync(request.Email, token, request.Language, isNewLink: false, HttpContext.RequestAborted); + return Ok(new { inviteLink, mail = MailBody(mail) }); } /// @@ -142,16 +171,44 @@ public class UsersController : ControllerBase [HttpPost("{invitationId:guid}/regenerate-invite")] public async Task RegenerateInvite(Guid invitationId) { - var invitationRole = await GetInvitationRoleAsync(invitationId); - if (invitationRole is null) return NotFound(); + var invitation = await GetInvitationAsync(invitationId); + if (invitation is null) return NotFound(); - if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), invitationRole)) + if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), invitation.Role)) return Forbid(); var token = await _invitationService.RegenerateInvitationAsync(invitationId); if (token is null) return NotFound(); - return Ok(new { inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}" }); + var mail = await _mail.SendInvitationAsync(invitation.Email, token, invitation.Language, isNewLink: true, HttpContext.RequestAborted); + return Ok(new { inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}", mail = MailBody(mail) }); + } + + /// + /// Sends the invitation mail again: the current link while it is valid, a freshly created one (new + /// token and lifetime) when it has expired. Returns the link and the mail result, so a failed mail + /// can be retried and the link can still be copied. + /// + [HttpPost("{invitationId:guid}/resend-invite")] + public async Task ResendInvite(Guid invitationId) + { + var invitation = await GetInvitationAsync(invitationId); + if (invitation is null) return NotFound(); + + if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), invitation.Role)) + return Forbid(); + + var token = invitation.Token; + var isNewLink = invitation.IsExpired; + if (isNewLink) + { + var fresh = await _invitationService.RegenerateInvitationAsync(invitationId); + if (fresh is null) return NotFound(); + token = fresh; + } + + var mail = await _mail.SendInvitationAsync(invitation.Email, token, invitation.Language, isNewLink, HttpContext.RequestAborted); + return Ok(new { inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}", mail = MailBody(mail) }); } [HttpPut("{userId:guid}/role")] @@ -194,6 +251,10 @@ public class UsersController : ControllerBase await _userManager.RemoveFromRolesAsync(target, targetRoles); await _userManager.AddToRoleAsync(target, request.NewRole); + + if (targetRole != request.NewRole) + await _mail.SendRoleChangedAsync(target, request.NewRole, HttpContext.RequestAborted); + return Ok(); } @@ -218,11 +279,19 @@ public class UsersController : ControllerBase return BadRequest(new { detail = "At least one Owner must remain." }); } + var wasActive = target.IsActive; target.IsActive = request.IsActive; var result = await _userManager.UpdateAsync(target); if (!result.Succeeded) return StatusCode(500, new { detail = "Failed to update user." }); + // A notice only on a real change; a mail failure never fails the action. + if (wasActive != request.IsActive) + { + if (request.IsActive) await _mail.SendAccountReactivatedAsync(target, HttpContext.RequestAborted); + else await _mail.SendAccountDeactivatedAsync(target, HttpContext.RequestAborted); + } + return Ok(); } @@ -282,9 +351,16 @@ public class UsersController : ControllerBase return roles.FirstOrDefault() ?? UserManagementRules.User; } - private async Task GetInvitationRoleAsync(Guid invitationId) + private async Task GetInvitationRoleAsync(Guid invitationId) => + (await GetInvitationAsync(invitationId))?.Role; + + private async Task GetInvitationAsync(Guid invitationId) { var all = await _invitationService.GetAllPendingInvitationsAsync(); - return all?.FirstOrDefault(i => i.Id == invitationId)?.Role; + return all?.FirstOrDefault(i => i.Id == invitationId); } + + /// The mail result for the client; null when this site has no mail (nothing to show). + private static object? MailBody(MailSendResult result) => + result.ErrorCode == MailSendResult.Disabled ? null : new { sent = result.Sent, error = result.ErrorCode }; }