mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationPolicies"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationPoliciesTests
|
||||
{
|
||||
[Fact]
|
||||
public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
|
||||
Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION);
|
||||
Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION);
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationServiceTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AuthorizationService _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
|
||||
/// </summary>
|
||||
public AuthorizationServiceTests()
|
||||
{
|
||||
_userId = Guid.NewGuid();
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
_httpContext = new DefaultHttpContext();
|
||||
_httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanCreateLibraries]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanViewUsers]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "User", permissions: []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: []));
|
||||
|
||||
// Act
|
||||
await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GetAuthorizationResponse>(
|
||||
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAJsonRequest_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "application/json";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<BrokenCircuitException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsAnAuthorizationStatusDuringAPageNavigation_ShouldRethrow(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, statusCode)));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsNotFoundDuringAPageNavigation_ShouldThrowCurrentUserAuthorizationException()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1")));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<CurrentUserAuthorizationException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InitializationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InitializationHandlerTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly InitializationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InitializationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public InitializationHandlerTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = new InitializationHandler(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new BrokenCircuitException()));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiReturnsUnauthorizedDuringAPageNavigation_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.Unauthorized)));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => _sut.HandleAsync(context));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
|
||||
AuthorizationHandlerContext context = CreateContext(httpContext);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a page navigation HTTP context.
|
||||
/// </summary>
|
||||
/// <returns>The created HTTP context.</returns>
|
||||
private static DefaultHttpContext CreateHttpContext()
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Request.Headers.Accept = "text/html";
|
||||
return httpContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates the initialization requirement.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context of the request being authorized.</param>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext(HttpContext httpContext)
|
||||
{
|
||||
return new AuthorizationHandlerContext(
|
||||
[new InitializationRequirement()],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
httpContext);
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PermissionAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PermissionAuthorizationHandlerTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly PermissionAuthorizationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PermissionAuthorizationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public PermissionAuthorizationHandlerTests()
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
|
||||
};
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheUserHoldsTheRequiredPermission_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnAdministratorLacksTheRequiredPermission_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
// The API lets administrators do what the permission allows even without holding it, so the Web must not deny them.
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAUserIsNeitherAnAdministratorNorHoldsTheRequiredPermission_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
// The authorization service returns no role or permission when the API is unreachable, and marks the request instead.
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.User = new ClaimsPrincipal();
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates a requirement for the permission to manage media libraries.
|
||||
/// </summary>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext()
|
||||
{
|
||||
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
|
||||
return new AuthorizationHandlerContext(
|
||||
[new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RoleAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleAuthorizationHandlerTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly DefaultHttpContext _httpContext;
|
||||
private readonly RoleAuthorizationHandler _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoleAuthorizationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RoleAuthorizationHandlerTests()
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
|
||||
};
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
httpContextAccessor.HttpContext.Returns(_httpContext);
|
||||
_sut = new RoleAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheUserBelongsToTheRequiredRole_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheUserBelongsToNoneOfTheRequiredRoles_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
|
||||
{
|
||||
// Arrange
|
||||
// The authorization service returns no role when the API is unreachable, and marks the request instead.
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.True(context.HasSucceeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
_httpContext.User = new ClaimsPrincipal();
|
||||
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
AuthorizationHandlerContext context = CreateContext();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.False(context.HasSucceeded);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization context that evaluates a requirement for the administrator role.
|
||||
/// </summary>
|
||||
/// <returns>The created authorization context.</returns>
|
||||
private static AuthorizationHandlerContext CreateContext()
|
||||
{
|
||||
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
|
||||
return new AuthorizationHandlerContext(
|
||||
[new RoleRequirement("Admin")],
|
||||
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
|
||||
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user