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 <noreply@anthropic.com>
This commit is contained in:
@@ -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<OutgoingMail> Sent { get; } = [];
|
||||
public MailSendResult Result { get; set; } = MailSendResult.Ok;
|
||||
public bool Throw { get; set; }
|
||||
|
||||
public Task<MailSendResult> 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<ISiteSettingsService>();
|
||||
|
||||
public IdentityMailServiceTests() =>
|
||||
_settings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).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<IdentityMailService>.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("<img");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://t.nl", "/invite/complete?token=a", "https://t.nl/admin/invite/complete?token=a")]
|
||||
[InlineData("https://t.nl/", "/login", "https://t.nl/admin/login")]
|
||||
[InlineData("https://t.nl", "login", "https://t.nl/admin/login")]
|
||||
public void BuildLink_PutsTheAdminBasePathBetweenSiteAndPath(string baseUrl, string path, string expected) =>
|
||||
IdentityMailService.BuildLink(baseUrl, path).Should().Be(expected);
|
||||
}
|
||||
@@ -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<IMigrationsAssembly>().Migrations.Keys.OrderBy(k => k).ToList();
|
||||
var previous = migrations[^2];
|
||||
var migrator = db.GetService<IMigrator>();
|
||||
|
||||
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<bool> ColumnExists(ApplicationDbContext db, string table, string column)
|
||||
{
|
||||
var rows = await db.Database
|
||||
.SqlQuery<int>($"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<bool> TableExists(ApplicationDbContext db, string table)
|
||||
{
|
||||
var rows = await db.Database
|
||||
|
||||
@@ -79,7 +79,7 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
|
||||
{
|
||||
using var scope = _host.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
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<ApplicationDbContext>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
|
||||
|
||||
await _service.CompleteInvitationAsync(token, "SafePassword123!", "Naam");
|
||||
|
||||
await _userManager.Received(1).CreateAsync(Arg.Is<ApplicationUser>(u => u.PreferredLanguage == "en"), "SafePassword123!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The real chain end to end (real Identity password handling, real tokens from <see cref="AuthService"/>,
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<ApplicationDbContext>(o => o.UseInMemoryDatabase(_dbName));
|
||||
services.AddIdentityCore<ApplicationUser>().AddRoles<ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>();
|
||||
services.Configure<JwtSettings>(o =>
|
||||
{
|
||||
o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes;
|
||||
});
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
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<UserManager<ApplicationUser>>();
|
||||
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<HttpStatusCode> 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<T> InScope<T>(Func<IAuthService, Task<T>> action)
|
||||
{
|
||||
using var scope = _host.Services.CreateScope();
|
||||
return await action(scope.ServiceProvider.GetRequiredService<IAuthService>());
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,11 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
// Hernoemen van standaard Identity tabellen (NFR-ID-MAINT-01)
|
||||
builder.Entity<ApplicationUser>(entity => { entity.ToTable("Users"); });
|
||||
builder.Entity<ApplicationUser>(entity =>
|
||||
{
|
||||
entity.ToTable("Users");
|
||||
entity.Property(e => e.PreferredLanguage).HasMaxLength(8);
|
||||
});
|
||||
builder.Entity<ApplicationRole>(entity => { entity.ToTable("Roles"); });
|
||||
builder.Entity<IdentityUserRole<Guid>>(entity => { entity.ToTable("UserRoles"); });
|
||||
builder.Entity<IdentityUserClaim<Guid>>(entity => { entity.ToTable("UserClaims"); });
|
||||
@@ -74,6 +78,7 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
|
||||
entity.HasIndex(e => 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)
|
||||
|
||||
@@ -28,6 +28,7 @@ public static class EmailServiceCollectionExtensions
|
||||
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
|
||||
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
|
||||
services.TryAddScoped<ISiteSettingsService, SiteSettingsService>();
|
||||
services.TryAddScoped<IIdentityMailService, IdentityMailService>();
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IIdentityMailService
|
||||
{
|
||||
/// <summary>True when this site can send mail (an SMTP host is configured).</summary>
|
||||
bool IsEnabled { get; }
|
||||
|
||||
Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class IdentityMailService(
|
||||
IEmailSender sender,
|
||||
IMailTemplateRenderer renderer,
|
||||
ILanguageResolver languages,
|
||||
ISiteSettingsService siteSettings,
|
||||
IOptions<EmailOptions> email,
|
||||
IOptions<AppMailOptions> app,
|
||||
IOptions<InvitationSettings> invitation,
|
||||
ILogger<IdentityMailService> logger) : IIdentityMailService
|
||||
{
|
||||
public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host);
|
||||
|
||||
public Task<MailSendResult> 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<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default) =>
|
||||
SendAsync(MailKind.AccountDeactivated, user.Email, user.PreferredLanguage, user.DisplayName, null, null, null, ct);
|
||||
|
||||
public Task<MailSendResult> SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default) =>
|
||||
SendAsync(MailKind.AccountReactivated, user.Email, user.PreferredLanguage, user.DisplayName, "/login", null, null, ct);
|
||||
|
||||
public Task<MailSendResult> SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default) =>
|
||||
SendAsync(MailKind.RoleChanged, user.Email, user.PreferredLanguage, user.DisplayName, null, null, newRole, ct);
|
||||
|
||||
private async Task<MailSendResult> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Public site address + the admin base path + the app path (the admin is mounted under /admin).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ namespace SlpModularCms.Core.Identity.Authorization;
|
||||
/// </remarks>
|
||||
public static class ActiveUserTokenValidation
|
||||
{
|
||||
/// <summary>Claim carrying the user's security stamp at the moment the access token was issued.</summary>
|
||||
public const string StampClaim = "stamp";
|
||||
|
||||
/// <summary>
|
||||
/// 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<ApplicationDbContext>();
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ public class ApplicationUser : IdentityUser<Guid>
|
||||
/// </summary>
|
||||
public string? DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Voorkeurstaal van de gebruiker (nl of en), ook voor e-mails. Null = standaardtaal van de site.
|
||||
/// </summary>
|
||||
public string? PreferredLanguage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Navigatie-eigenschap naar module-specifieke rechten.
|
||||
/// </summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Taal van de uitnodigingsmail en voorkeurstaal van het nieuwe account (nl of en); null = sitestandaard.</summary>
|
||||
public string? Language { get; set; }
|
||||
|
||||
public DateTimeOffset ExpiryDate { get; set; }
|
||||
public bool IsAccepted { get; set; }
|
||||
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -23,5 +23,6 @@ public record UserResponse(
|
||||
string Email,
|
||||
string Name,
|
||||
string Role,
|
||||
bool IsActive
|
||||
bool IsActive,
|
||||
string? Language = null
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -10,7 +10,7 @@ public interface IInvitationService
|
||||
/// <summary>
|
||||
/// Maakt een nieuwe uitnodiging aan en retourneert het token.
|
||||
/// </summary>
|
||||
Task<string> CreateInvitationAsync(string email, string role);
|
||||
Task<string> CreateInvitationAsync(string email, string role, string? language = null);
|
||||
|
||||
/// <summary>
|
||||
/// Valideert of een uitnodigings-token nog geldig is.
|
||||
|
||||
@@ -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<string> CreateInvitationAsync(string email, string role)
|
||||
public async Task<string> 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();
|
||||
}
|
||||
|
||||
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Core.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Core.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20261108180809_AddLanguagePreference")]
|
||||
partial class AddLanguagePreference
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.9")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 64);
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("FriendlyName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Xml")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("DataProtectionKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("RoleClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ClaimType")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ClaimValue")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("UserClaims", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("ProviderKey")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("ProviderDisplayName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("LoginProvider", "ProviderKey");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("UserLogins", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("LoginProvider")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("UserId", "LoginProvider", "Name");
|
||||
|
||||
b.ToTable("UserTokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationRole", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("PreferredLanguage")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("varchar(8)");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex");
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.GlobalAvailabilityState", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("LastUpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("AvailabilityState", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.Invitation", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiryDate")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsAccepted")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("varchar(8)");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Invitations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("ModuleName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.Property<string>("Permission")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.HasKey("UserId", "ModuleName", "Permission");
|
||||
|
||||
b.ToTable("ModulePermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("CreatedByIp")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiryDate")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsUsed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.SiteSettings.SiteSettingsEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("MailFromAddress")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.Property<string>("MailFromName")
|
||||
.HasMaxLength(80)
|
||||
.HasColumnType("varchar(80)");
|
||||
|
||||
b.Property<DateTimeOffset>("UpdatedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("UpdatedBy")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("varchar(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("SiteSettings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
|
||||
.WithMany("ModulePermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
|
||||
{
|
||||
b.Navigation("ModulePermissions");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Core.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddLanguagePreference : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "PreferredLanguage",
|
||||
table: "Users",
|
||||
type: "varchar(8)",
|
||||
maxLength: 8,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Language",
|
||||
table: "Invitations",
|
||||
type: "varchar(8)",
|
||||
maxLength: 8,
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PreferredLanguage",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Language",
|
||||
table: "Invitations");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,6 +214,10 @@ namespace SlpModularCms.Core.Migrations
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("PreferredLanguage")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("varchar(8)");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
@@ -279,6 +283,10 @@ namespace SlpModularCms.Core.Migrations
|
||||
b.Property<bool>("IsAccepted")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("varchar(8)");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class UsersControllerMailTests : IDisposable
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<ApplicationRole> _roleManager;
|
||||
private readonly IInvitationService _invitations = Substitute.For<IInvitationService>();
|
||||
private readonly IIdentityMailService _mail = Substitute.For<IIdentityMailService>();
|
||||
|
||||
public UsersControllerMailTests()
|
||||
{
|
||||
_context = new ApplicationDbContext(new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
|
||||
_userManager = new UserManager<ApplicationUser>(
|
||||
new UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, Guid>(_context),
|
||||
Options.Create(new IdentityOptions()), new PasswordHasher<ApplicationUser>(),
|
||||
Array.Empty<IUserValidator<ApplicationUser>>(), Array.Empty<IPasswordValidator<ApplicationUser>>(),
|
||||
new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), null!,
|
||||
NullLogger<UserManager<ApplicationUser>>.Instance);
|
||||
_roleManager = new RoleManager<ApplicationRole>(
|
||||
new RoleStore<ApplicationRole, ApplicationDbContext, Guid>(_context),
|
||||
Array.Empty<IRoleValidator<ApplicationRole>>(), new UpperInvariantLookupNormalizer(),
|
||||
new IdentityErrorDescriber(), NullLogger<RoleManager<ApplicationRole>>.Instance);
|
||||
|
||||
_invitations.GetAllPendingInvitationsAsync().Returns(new List<PendingInvitationInfo>());
|
||||
_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<ApplicationUser> 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<PendingInvitationInfo>
|
||||
{
|
||||
new(id, "invited@test.com", role, "old-token", DateTimeOffset.UtcNow.AddDays(-2), expired, language)
|
||||
});
|
||||
|
||||
private static T Prop<T>(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<OkObjectResult>().Subject.Value;
|
||||
Prop<string>(body, "inviteLink").Should().Be("/invite/complete?token=tok");
|
||||
var mail = Prop<object>(body, "mail");
|
||||
Prop<bool>(mail, "sent").Should().BeTrue();
|
||||
await _mail.Received(1).SendInvitationAsync("new@test.com", "tok", "en", false, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<OkObjectResult>().Subject.Value;
|
||||
Prop<string>(body, "inviteLink").Should().NotBeNullOrEmpty();
|
||||
var mail = Prop<object>(body, "mail");
|
||||
Prop<bool>(mail, "sent").Should().BeFalse();
|
||||
Prop<string>(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<object?>(result.Should().BeOfType<OkObjectResult>().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<BadRequestObjectResult>();
|
||||
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<string>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "inviteLink").Should().Contain("new-token");
|
||||
await _mail.Received(1).SendInvitationAsync("invited@test.com", "new-token", "en", true, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<string>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "inviteLink").Should().Contain("old-token");
|
||||
await _invitations.DidNotReceive().RegenerateInvitationAsync(Arg.Any<Guid>());
|
||||
await _mail.Received(1).SendInvitationAsync("invited@test.com", "old-token", "en", false, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<string>(result.Should().BeOfType<OkObjectResult>().Subject.Value, "inviteLink").Should().Contain("fresh");
|
||||
await _mail.Received(1).SendInvitationAsync("invited@test.com", "fresh", "en", true, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<OkObjectResult>().Subject.Value;
|
||||
|
||||
Prop<string>(Prop<object>(body, "mail"), "error").Should().Be("auth_failed");
|
||||
Prop<string>(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<ForbidResult>();
|
||||
(await As(admin).ResendInvite(Guid.NewGuid())).Should().BeOfType<NotFoundResult>();
|
||||
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<ApplicationUser>(u => u.Id == user.Id), Arg.Any<CancellationToken>());
|
||||
|
||||
await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(false)); // already inactive: no second notice
|
||||
await _mail.Received(1).SendAccountDeactivatedAsync(Arg.Any<ApplicationUser>(), Arg.Any<CancellationToken>());
|
||||
|
||||
await As(owner).SetUserActive(user.Id, new SetUserActiveRequest(true));
|
||||
await _mail.Received(1).SendAccountReactivatedAsync(Arg.Is<ApplicationUser>(u => u.Id == user.Id), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<OkResult>();
|
||||
|
||||
(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<ApplicationUser>(u => u.Id == user.Id), "Administrator", Arg.Any<CancellationToken>());
|
||||
|
||||
await As(owner).ChangeRole(user.Id, new ChangeRoleRequest("Administrator"));
|
||||
await _mail.Received(1).SendRoleChangedAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<OkResult>();
|
||||
|
||||
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<OkObjectResult>().Subject.Value.Should().BeOfType<UserDto>().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<BadRequestObjectResult>();
|
||||
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<string>()).Returns((false, null));
|
||||
|
||||
var result = await As(owner).GetUsers();
|
||||
|
||||
var list = result.Should().BeOfType<OkObjectResult>().Subject.Value.Should().BeAssignableTo<IEnumerable<UserDto>>().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");
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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<IIdentityMailService>());
|
||||
controller.ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = new DefaultHttpContext
|
||||
|
||||
@@ -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<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<ApplicationRole> _roleManager;
|
||||
private readonly IInvitationService _invitationService = Substitute.For<IInvitationService>();
|
||||
private readonly IIdentityMailService _mail = Substitute.For<IIdentityMailService>();
|
||||
|
||||
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"));
|
||||
|
||||
@@ -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<ApplicationUser> _userManager;
|
||||
private readonly IIdentityMailService _mail;
|
||||
|
||||
public UsersController(IInvitationService invitationService, UserManager<ApplicationUser> userManager)
|
||||
public UsersController(
|
||||
IInvitationService invitationService,
|
||||
UserManager<ApplicationUser> 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) });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -142,16 +171,44 @@ public class UsersController : ControllerBase
|
||||
[HttpPost("{invitationId:guid}/regenerate-invite")]
|
||||
public async Task<IActionResult> 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) });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[HttpPost("{invitationId:guid}/resend-invite")]
|
||||
public async Task<IActionResult> 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<string?> GetInvitationRoleAsync(Guid invitationId)
|
||||
private async Task<string?> GetInvitationRoleAsync(Guid invitationId) =>
|
||||
(await GetInvitationAsync(invitationId))?.Role;
|
||||
|
||||
private async Task<PendingInvitationInfo?> GetInvitationAsync(Guid invitationId)
|
||||
{
|
||||
var all = await _invitationService.GetAllPendingInvitationsAsync();
|
||||
return all?.FirstOrDefault(i => i.Id == invitationId)?.Role;
|
||||
return all?.FirstOrDefault(i => i.Id == invitationId);
|
||||
}
|
||||
|
||||
/// <summary>The mail result for the client; null when this site has no mail (nothing to show).</summary>
|
||||
private static object? MailBody(MailSendResult result) =>
|
||||
result.ErrorCode == MailSendResult.Disabled ? null : new { sent = result.Sent, error = result.ErrorCode };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user