Identity e-mail notifications, ASF-hosting en testfixes (run 636) #11
@@ -0,0 +1,67 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data.MySqlClient;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Evidence that an invitation keeps its full lifetime through the real MySQL/MariaDB storage:
|
||||
/// <c>DateTimeOffset</c> is stored in a <c>datetime</c> column (no offset), so a provider that
|
||||
/// stored local time but read it as UTC (or the reverse) would silently shorten or lengthen it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Needs a reachable MariaDB, taken from <c>ConnectionStrings__DefaultConnection</c> (set in CI; the
|
||||
/// same variable the Api tests use). It uses its OWN database, created and dropped here, never the
|
||||
/// one named in the variable. Without the variable the test does nothing, so a plain
|
||||
/// <c>dotnet test</c> on a machine without MariaDB stays green.
|
||||
/// </remarks>
|
||||
public class DateTimeOffsetRoundTripTests
|
||||
{
|
||||
private static string? ScratchConnectionString()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
|
||||
if (string.IsNullOrWhiteSpace(raw)) return null;
|
||||
var builder = new MySqlConnectionStringBuilder(raw) { Database = "roundtrip_datetime_probe" };
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(-5)]
|
||||
public async Task ExpiryDate_SurvivesTheDatabase_WhateverOffsetItWasWrittenWith(int offsetHours)
|
||||
{
|
||||
var cs = ScratchConnectionString();
|
||||
if (cs is null) return; // no MariaDB available here, see remarks
|
||||
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseMySQL(cs).Options;
|
||||
var instant = DateTimeOffset.UtcNow.AddHours(24);
|
||||
var written = instant.ToOffset(TimeSpan.FromHours(offsetHours));
|
||||
|
||||
await using (var db = new ApplicationDbContext(options))
|
||||
{
|
||||
await db.Database.EnsureDeletedAsync();
|
||||
await db.Database.EnsureCreatedAsync();
|
||||
db.Invitations.Add(new Invitation { Email = "a@b.nl", Role = "User", Token = "t", ExpiryDate = written });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using var db = new ApplicationDbContext(options);
|
||||
var read = (await db.Invitations.AsNoTracking().SingleAsync()).ExpiryDate;
|
||||
|
||||
// The column keeps whole seconds only, so compare within a second.
|
||||
(read - instant).Duration().Should().BeLessThan(TimeSpan.FromSeconds(1.5));
|
||||
(read - DateTimeOffset.UtcNow).TotalHours.Should().BeApproximately(24, 0.01);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await using var cleanup = new ApplicationDbContext(options);
|
||||
await cleanup.Database.EnsureDeletedAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,4 +363,35 @@ public class InvitationServiceTests
|
||||
(await _service.DeleteInvitationByIdAsync(inv.Id)).Should().BeTrue();
|
||||
(await _context.Invitations.AnyAsync()).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvitationAsync_GivesANewTokenAndLifetime_AndTheOldLinkStopsWorking()
|
||||
{
|
||||
var oldToken = await _service.CreateInvitationAsync("again@example.com", "User");
|
||||
var inv = await _context.Invitations.SingleAsync();
|
||||
inv.ExpiryDate = DateTimeOffset.UtcNow.AddHours(-3); // expired
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var newToken = await _service.RegenerateInvitationAsync(inv.Id);
|
||||
|
||||
newToken.Should().NotBeNullOrEmpty().And.NotBe(oldToken);
|
||||
(await _service.ValidateInvitationAsync(oldToken)).Should().BeFalse();
|
||||
(await _service.ValidateInvitationAsync(newToken!)).Should().BeTrue();
|
||||
var reloaded = await _context.Invitations.AsNoTracking().SingleAsync();
|
||||
(reloaded.ExpiryDate - DateTimeOffset.UtcNow).Should().BeCloseTo(TimeSpan.FromHours(24), TimeSpan.FromMinutes(1));
|
||||
reloaded.Email.Should().Be("again@example.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvitationAsync_ReturnsNull_ForUnknownOrAcceptedInvitations()
|
||||
{
|
||||
(await _service.RegenerateInvitationAsync(Guid.NewGuid())).Should().BeNull();
|
||||
|
||||
var token = await _service.CreateInvitationAsync("done@example.com", "User");
|
||||
var inv = await _context.Invitations.SingleAsync(i => i.Token == token);
|
||||
inv.IsAccepted = true;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
(await _service.RegenerateInvitationAsync(inv.Id)).Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace SlpModularCms.Core.Identity.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Who may act on whom in user management. One place, enforced by the API and mirrored by the UI.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An Owner may manage everyone. An Administrator may manage only plain Users, never another
|
||||
/// Administrator or an Owner, and may not hand out the Owner role. The "at least one Owner must
|
||||
/// remain" rule is separate and stays in the controller.
|
||||
/// </remarks>
|
||||
public static class UserManagementRules
|
||||
{
|
||||
public const string Owner = "Owner";
|
||||
public const string Administrator = "Administrator";
|
||||
public const string User = "User";
|
||||
|
||||
/// <summary>May the requester delete, (de)activate, re-role or withdraw an invitation of a target holding this role?</summary>
|
||||
public static bool CanManage(string requesterRole, string targetRole) =>
|
||||
requesterRole == Owner || (requesterRole == Administrator && targetRole == User);
|
||||
|
||||
/// <summary>May the requester give somebody (or an invitation) this role?</summary>
|
||||
public static bool CanAssign(string requesterRole, string role) =>
|
||||
requesterRole == Owner || (requesterRole == Administrator && role != Owner);
|
||||
}
|
||||
@@ -46,4 +46,10 @@ public interface IInvitationService
|
||||
/// Wijzigt de rol van een pending uitnodiging. Retourneert false als niet gevonden.
|
||||
/// </summary>
|
||||
Task<bool> UpdateInvitationRoleAsync(Guid invitationId, string newRole);
|
||||
|
||||
/// <summary>
|
||||
/// Geeft een openstaande (ook verlopen) uitnodiging een nieuw token en een nieuwe geldigheid; het oude
|
||||
/// token werkt daarna niet meer. Retourneert het nieuwe token, of null als niet gevonden.
|
||||
/// </summary>
|
||||
Task<string?> RegenerateInvitationAsync(Guid invitationId);
|
||||
}
|
||||
|
||||
@@ -157,6 +157,18 @@ public class InvitationService : IInvitationService
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<string?> RegenerateInvitationAsync(Guid invitationId)
|
||||
{
|
||||
var invitation = await _context.Invitations
|
||||
.FirstOrDefaultAsync(i => i.Id == invitationId && !i.IsAccepted);
|
||||
if (invitation is null) return null;
|
||||
|
||||
invitation.Token = GenerateSecureToken();
|
||||
invitation.ExpiryDate = DateTimeOffset.UtcNow.AddHours(_settings.ExpiryHours);
|
||||
await _context.SaveChangesAsync();
|
||||
return invitation.Token;
|
||||
}
|
||||
|
||||
private static string GenerateSecureToken()
|
||||
{
|
||||
var bytes = new byte[32];
|
||||
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
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.Identity.Authorization;
|
||||
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>
|
||||
/// Who may act on whom, enforced by the API itself (the UI only mirrors it): an Administrator reaches
|
||||
/// plain Users only; Owners and Administrators are an Owner's to manage; the last Owner stays.
|
||||
/// </summary>
|
||||
public class UsersControllerRoleHierarchyTests : IDisposable
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<ApplicationRole> _roleManager;
|
||||
private readonly IInvitationService _invitations = Substitute.For<IInvitationService>();
|
||||
|
||||
public UsersControllerRoleHierarchyTests()
|
||||
{
|
||||
var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_context = new ApplicationDbContext(dbOptions);
|
||||
|
||||
_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>());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_userManager.Dispose();
|
||||
_roleManager.Dispose();
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
private async Task<ApplicationUser> Add(string email, string role)
|
||||
{
|
||||
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 = email, IsActive = true, 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);
|
||||
controller.ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, caller.UserName!)], "Test"))
|
||||
}
|
||||
};
|
||||
return controller;
|
||||
}
|
||||
|
||||
private void OpenInvitation(Guid id, string role) =>
|
||||
_invitations.GetAllPendingInvitationsAsync().Returns(new List<PendingInvitationInfo>
|
||||
{
|
||||
new(id, "invited@test.com", role, "tok", DateTimeOffset.UtcNow)
|
||||
});
|
||||
|
||||
// --- rules ---
|
||||
|
||||
[Theory]
|
||||
[InlineData("Owner", "Owner", true)]
|
||||
[InlineData("Owner", "Administrator", true)]
|
||||
[InlineData("Owner", "User", true)]
|
||||
[InlineData("Administrator", "User", true)]
|
||||
[InlineData("Administrator", "Administrator", false)]
|
||||
[InlineData("Administrator", "Owner", false)]
|
||||
[InlineData("User", "User", false)]
|
||||
public void CanManage_FollowsTheHierarchy(string requester, string target, bool expected) =>
|
||||
UserManagementRules.CanManage(requester, target).Should().Be(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData("Owner", "Owner", true)]
|
||||
[InlineData("Administrator", "Administrator", true)]
|
||||
[InlineData("Administrator", "User", true)]
|
||||
[InlineData("Administrator", "Owner", false)]
|
||||
public void CanAssign_AdministratorNeverHandsOutOwner(string requester, string role, bool expected) =>
|
||||
UserManagementRules.CanAssign(requester, role).Should().Be(expected);
|
||||
|
||||
// --- delete ---
|
||||
|
||||
[Theory]
|
||||
[InlineData("Owner")]
|
||||
[InlineData("Administrator")]
|
||||
public async Task Administrator_CannotDelete_OwnerOrAdministrator(string targetRole)
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var target = await Add("target@test.com", targetRole);
|
||||
|
||||
(await As(admin).DeleteUser(target.Id)).Should().BeOfType<ForbidResult>();
|
||||
|
||||
(await _userManager.FindByIdAsync(target.Id.ToString())).Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CanDelete_PlainUser()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var target = await Add("target@test.com", "User");
|
||||
|
||||
(await As(admin).DeleteUser(target.Id)).Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Administrator")]
|
||||
[InlineData("User")]
|
||||
public async Task Owner_CanDelete_AdministratorAndUser(string targetRole)
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var target = await Add("target@test.com", targetRole);
|
||||
|
||||
(await As(owner).DeleteUser(target.Id)).Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CannotWithdraw_AnInvitationForAnAdministrator_ButCanForAUser()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var id = Guid.NewGuid();
|
||||
|
||||
OpenInvitation(id, "Administrator");
|
||||
(await As(admin).DeleteUser(id)).Should().BeOfType<ForbidResult>();
|
||||
await _invitations.DidNotReceive().DeleteInvitationByIdAsync(Arg.Any<Guid>());
|
||||
|
||||
OpenInvitation(id, "User");
|
||||
_invitations.DeleteInvitationByIdAsync(id).Returns(true);
|
||||
(await As(admin).DeleteUser(id)).Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Owner_CanWithdraw_AnyInvitation()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
OpenInvitation(id, "Administrator");
|
||||
_invitations.DeleteInvitationByIdAsync(id).Returns(true);
|
||||
|
||||
(await As(owner).DeleteUser(id)).Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
// --- deactivate ---
|
||||
|
||||
[Theory]
|
||||
[InlineData("Owner")]
|
||||
[InlineData("Administrator")]
|
||||
public async Task Administrator_CannotDeactivate_OwnerOrAdministrator(string targetRole)
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var target = await Add("target@test.com", targetRole);
|
||||
|
||||
(await As(admin).SetUserActive(target.Id, new SetUserActiveRequest(false))).Should().BeOfType<ForbidResult>();
|
||||
|
||||
(await _userManager.FindByIdAsync(target.Id.ToString()))!.IsActive.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CanDeactivate_PlainUser()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var target = await Add("target@test.com", "User");
|
||||
|
||||
(await As(admin).SetUserActive(target.Id, new SetUserActiveRequest(false))).Should().BeOfType<OkResult>();
|
||||
|
||||
(await _userManager.FindByIdAsync(target.Id.ToString()))!.IsActive.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Owner_CanDeactivate_Administrator()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var target = await Add("target@test.com", "Administrator");
|
||||
|
||||
(await As(owner).SetUserActive(target.Id, new SetUserActiveRequest(false))).Should().BeOfType<OkResult>();
|
||||
}
|
||||
|
||||
// --- change role ---
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CannotChangeTheRole_OfAnotherAdministratorOrOwner()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var otherAdmin = await Add("other@test.com", "Administrator");
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
|
||||
(await As(admin).ChangeRole(otherAdmin.Id, new ChangeRoleRequest("User"))).Should().BeOfType<ForbidResult>();
|
||||
(await As(admin).ChangeRole(owner.Id, new ChangeRoleRequest("User"))).Should().BeOfType<ForbidResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CannotMakeAnyoneOwner_NotEvenAPlainUser()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var user = await Add("user@test.com", "User");
|
||||
|
||||
(await As(admin).ChangeRole(user.Id, new ChangeRoleRequest("Owner"))).Should().BeOfType<ForbidResult>();
|
||||
|
||||
(await _userManager.GetRolesAsync(user)).Should().ContainSingle().Which.Should().Be("User");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CanPromoteAUserToAdministrator_AndStepDownThemselves()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var user = await Add("user@test.com", "User");
|
||||
|
||||
(await As(admin).ChangeRole(user.Id, new ChangeRoleRequest("Administrator"))).Should().BeOfType<OkResult>();
|
||||
(await As(admin).ChangeRole(admin.Id, new ChangeRoleRequest("User"))).Should().BeOfType<OkResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CannotChangeTheRole_OfAnInvitationForAnAdministrator()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var id = Guid.NewGuid();
|
||||
OpenInvitation(id, "Administrator");
|
||||
|
||||
(await As(admin).ChangeRole(id, new ChangeRoleRequest("User"))).Should().BeOfType<ForbidResult>();
|
||||
await _invitations.DidNotReceive().UpdateInvitationRoleAsync(Arg.Any<Guid>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheLastOwner_CannotBeDemoted_EvenByThemselves()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
|
||||
var result = await As(owner).ChangeRole(owner.Id, new ChangeRoleRequest("User"));
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>();
|
||||
(await _userManager.GetRolesAsync(owner)).Should().ContainSingle().Which.Should().Be("Owner");
|
||||
}
|
||||
|
||||
// --- invite ---
|
||||
|
||||
[Fact]
|
||||
public async Task Administrator_CannotInviteAnOwner_ButCanInviteAUser()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
_invitations.CreateInvitationAsync("new@test.com", "User").Returns("tok");
|
||||
|
||||
(await As(admin).Invite(new InviteUserRequest("new@test.com", "Owner"))).Should().BeOfType<ForbidResult>();
|
||||
await _invitations.DidNotReceive().CreateInvitationAsync("new@test.com", "Owner");
|
||||
|
||||
(await As(admin).Invite(new InviteUserRequest("new@test.com", "User"))).Should().BeOfType<OkObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Owner_CanInviteAnOwner()
|
||||
{
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
_invitations.CreateInvitationAsync("new@test.com", "Owner").Returns("tok");
|
||||
|
||||
(await As(owner).Invite(new InviteUserRequest("new@test.com", "Owner"))).Should().BeOfType<OkObjectResult>();
|
||||
}
|
||||
|
||||
// --- regenerate ---
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvite_ReturnsANewLink_ForAnOpenOrExpiredInvitation()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var id = Guid.NewGuid();
|
||||
OpenInvitation(id, "User");
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
|
||||
var result = await As(admin).RegenerateInvite(id);
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>().Which.Value
|
||||
.Should().BeEquivalentTo(new { inviteLink = "/invite/complete?token=new-token" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvite_IsNotFound_ForAnUnknownInvitation()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
|
||||
(await As(admin).RegenerateInvite(Guid.NewGuid())).Should().BeOfType<NotFoundResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerateInvite_FollowsTheSameHierarchy()
|
||||
{
|
||||
var admin = await Add("admin@test.com", "Administrator");
|
||||
var owner = await Add("owner@test.com", "Owner");
|
||||
var id = Guid.NewGuid();
|
||||
OpenInvitation(id, "Administrator");
|
||||
_invitations.RegenerateInvitationAsync(id).Returns("new-token");
|
||||
|
||||
(await As(admin).RegenerateInvite(id)).Should().BeOfType<ForbidResult>();
|
||||
(await As(owner).RegenerateInvite(id)).Should().BeOfType<OkObjectResult>();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
@@ -125,45 +126,61 @@ public class UsersController : ControllerBase
|
||||
[HttpPost("invite")]
|
||||
public async Task<IActionResult> Invite([FromBody] InviteUserRequest request)
|
||||
{
|
||||
var requesterRole = await GetRequesterRoleAsync();
|
||||
if (!UserManagementRules.CanAssign(requesterRole, request.Role))
|
||||
return Forbid();
|
||||
|
||||
var token = await _invitationService.CreateInvitationAsync(request.Email, request.Role);
|
||||
var inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}";
|
||||
return Ok(new { inviteLink });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Issues a fresh link for an open (or expired) invitation: new token and a new lifetime. The
|
||||
/// old link stops working. Until e-mail exists this is how an administrator re-sends one.
|
||||
/// </summary>
|
||||
[HttpPost("{invitationId:guid}/regenerate-invite")]
|
||||
public async Task<IActionResult> RegenerateInvite(Guid invitationId)
|
||||
{
|
||||
var invitationRole = await GetInvitationRoleAsync(invitationId);
|
||||
if (invitationRole is null) return NotFound();
|
||||
|
||||
if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), invitationRole))
|
||||
return Forbid();
|
||||
|
||||
var token = await _invitationService.RegenerateInvitationAsync(invitationId);
|
||||
if (token is null) return NotFound();
|
||||
|
||||
return Ok(new { inviteLink = $"/invite/complete?token={Uri.EscapeDataString(token)}" });
|
||||
}
|
||||
|
||||
[HttpPut("{userId:guid}/role")]
|
||||
public async Task<IActionResult> ChangeRole(Guid userId, [FromBody] ChangeRoleRequest request)
|
||||
{
|
||||
var requesterRole = await GetRequesterRoleAsync();
|
||||
if (!UserManagementRules.CanAssign(requesterRole, request.NewRole))
|
||||
return Forbid();
|
||||
|
||||
var target = await _userManager.FindByIdAsync(userId.ToString());
|
||||
|
||||
// Pending invite: no user account yet — update the invitation's role directly
|
||||
// Pending invite: no user account yet - update the invitation's role directly
|
||||
if (target is null)
|
||||
{
|
||||
var requesterEmailForInvite = User.Identity?.Name;
|
||||
var requesterForInvite = requesterEmailForInvite is not null
|
||||
? await _userManager.FindByNameAsync(requesterEmailForInvite)
|
||||
: null;
|
||||
var requesterRolesForInvite = requesterForInvite is not null
|
||||
? await _userManager.GetRolesAsync(requesterForInvite)
|
||||
: [];
|
||||
var requesterRoleForInvite = requesterRolesForInvite.FirstOrDefault() ?? "User";
|
||||
|
||||
// Admins cannot assign Owner role via invitation either
|
||||
if (requesterRoleForInvite == "Administrator" && request.NewRole == "Owner")
|
||||
var invitationRole = await GetInvitationRoleAsync(userId);
|
||||
if (invitationRole is not null && !UserManagementRules.CanManage(requesterRole, invitationRole))
|
||||
return Forbid();
|
||||
|
||||
var updated = await _invitationService.UpdateInvitationRoleAsync(userId, request.NewRole);
|
||||
return updated ? Ok() : NotFound();
|
||||
}
|
||||
|
||||
var requesterEmail = User.Identity?.Name;
|
||||
var requester = requesterEmail is not null ? await _userManager.FindByNameAsync(requesterEmail) : null;
|
||||
var requesterRoles = requester is not null ? await _userManager.GetRolesAsync(requester) : [];
|
||||
var requesterRole = requesterRoles.FirstOrDefault() ?? "User";
|
||||
|
||||
var targetRoles = await _userManager.GetRolesAsync(target);
|
||||
var targetRole = targetRoles.FirstOrDefault() ?? "User";
|
||||
|
||||
if (requesterRole == "Administrator" && targetRole != "User")
|
||||
// An Administrator may step down to User themselves; otherwise only plain Users are theirs to change.
|
||||
var isSelfDemotion = IsSelf(target) && requesterRole == UserManagementRules.Administrator
|
||||
&& request.NewRole == UserManagementRules.User;
|
||||
if (!isSelfDemotion && !UserManagementRules.CanManage(requesterRole, targetRole))
|
||||
return Forbid();
|
||||
|
||||
if (targetRole == "Owner" && request.NewRole != "Owner")
|
||||
@@ -186,19 +203,19 @@ public class UsersController : ControllerBase
|
||||
var target = await _userManager.FindByIdAsync(userId.ToString());
|
||||
if (target is null) return NotFound();
|
||||
|
||||
var requesterEmail = User.Identity?.Name;
|
||||
if (string.Equals(target.Email, requesterEmail, StringComparison.OrdinalIgnoreCase))
|
||||
if (IsSelf(target))
|
||||
return BadRequest(new { detail = "You cannot change your own active status." });
|
||||
|
||||
if (!request.IsActive)
|
||||
var targetRoles = await _userManager.GetRolesAsync(target);
|
||||
var targetRole = targetRoles.FirstOrDefault() ?? "User";
|
||||
if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), targetRole))
|
||||
return Forbid();
|
||||
|
||||
if (!request.IsActive && targetRoles.Contains("Owner"))
|
||||
{
|
||||
var targetRoles = await _userManager.GetRolesAsync(target);
|
||||
if (targetRoles.Contains("Owner"))
|
||||
{
|
||||
var ownerCount = (await _userManager.GetUsersInRoleAsync("Owner")).Count;
|
||||
if (ownerCount <= 1)
|
||||
return BadRequest(new { detail = "At least one Owner must remain." });
|
||||
}
|
||||
var ownerCount = (await _userManager.GetUsersInRoleAsync("Owner")).Count;
|
||||
if (ownerCount <= 1)
|
||||
return BadRequest(new { detail = "At least one Owner must remain." });
|
||||
}
|
||||
|
||||
target.IsActive = request.IsActive;
|
||||
@@ -217,15 +234,21 @@ public class UsersController : ControllerBase
|
||||
// If no user account found, try to cancel a pending invitation with this ID
|
||||
if (target is null)
|
||||
{
|
||||
var invitationRole = await GetInvitationRoleAsync(userId);
|
||||
if (invitationRole is not null && !UserManagementRules.CanManage(await GetRequesterRoleAsync(), invitationRole))
|
||||
return Forbid();
|
||||
|
||||
var deleted = await _invitationService.DeleteInvitationByIdAsync(userId);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
var requesterEmail = User.Identity?.Name;
|
||||
if (string.Equals(target.Email, requesterEmail, StringComparison.OrdinalIgnoreCase))
|
||||
if (IsSelf(target))
|
||||
return BadRequest(new { detail = "You cannot delete your own account." });
|
||||
|
||||
var targetRoles = await _userManager.GetRolesAsync(target);
|
||||
if (!UserManagementRules.CanManage(await GetRequesterRoleAsync(), targetRoles.FirstOrDefault() ?? "User"))
|
||||
return Forbid();
|
||||
|
||||
if (targetRoles.Contains("Owner"))
|
||||
{
|
||||
var ownerCount = (await _userManager.GetUsersInRoleAsync("Owner")).Count;
|
||||
@@ -242,4 +265,26 @@ public class UsersController : ControllerBase
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
private bool IsSelf(ApplicationUser target) =>
|
||||
string.Equals(target.Email, User.Identity?.Name, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The role of the caller from the database (not the token, which can be stale). A caller that cannot
|
||||
/// be resolved is treated as an Administrator, the most restricted role that reaches this controller.
|
||||
/// </summary>
|
||||
private async Task<string> GetRequesterRoleAsync()
|
||||
{
|
||||
var name = User.Identity?.Name;
|
||||
var requester = name is not null ? await _userManager.FindByNameAsync(name) : null;
|
||||
if (requester is null) return UserManagementRules.Administrator;
|
||||
|
||||
var roles = await _userManager.GetRolesAsync(requester);
|
||||
return roles.FirstOrDefault() ?? UserManagementRules.User;
|
||||
}
|
||||
|
||||
private async Task<string?> GetInvitationRoleAsync(Guid invitationId)
|
||||
{
|
||||
var all = await _invitationService.GetAllPendingInvitationsAsync();
|
||||
return all?.FirstOrDefault(i => i.Id == invitationId)?.Role;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user