mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 17:11:10 +00:00
211 lines
9.2 KiB
C#
211 lines
9.2 KiB
C#
#region ========================================================================= USING =====================================================================================
|
|
using Nemera.Application.Common.DataAccess.Entities.UsersManagement;
|
|
using Nemera.Application.Common.DataAccess.Seed;
|
|
using Nemera.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
|
using Nemera.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
|
using Nemera.Contracts.Fixtures.Core.Requests.Authentication;
|
|
using Nemera.Contracts.Requests.Authentication;
|
|
using Nemera.Contracts.Responses.Authentication;
|
|
using Nemera.DataAccess.Core.UoW;
|
|
using Nemera.Domain.SharedKernel.Common.Enums.Authorization;
|
|
using Nemera.Infrastructure.Core.Security;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
#endregion
|
|
|
|
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
|
|
|
// <summary>
|
|
/// Factory that extends <see cref="NemeraApiFactory"/> to provide authenticated HTTP clients for testing.
|
|
/// </summary>
|
|
[ExcludeFromCodeCoverage]
|
|
public class AuthenticatedNemeraApiFactory : NemeraApiFactory, IDisposable
|
|
{
|
|
private readonly PasswordHashService _hashService = new();
|
|
private readonly JsonSerializerOptions _jsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
private readonly UserEntityFixture _userEntityFixture = new();
|
|
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
|
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
|
private readonly LoginRequestFixture _loginRequestFixture = new();
|
|
|
|
/// <summary>
|
|
/// Gets the username of the currently created test user.
|
|
/// </summary>
|
|
public string? TestUsername { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Creates an HTTP client with authentication headers and a test user.
|
|
/// </summary>
|
|
/// <param name="permissions">The permissions granted directly to the test user, if any.</param>
|
|
/// <returns>An HTTP client configured with auth headers.</returns>
|
|
public async Task<HttpClient> CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
|
|
{
|
|
HttpClient client = CreateClient();
|
|
TestUsername = $"testuser_{Guid.NewGuid()}";
|
|
|
|
// Add the X-Forwarded-For header.
|
|
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
|
|
|
// Perform authentication.
|
|
await CreateAndAuthenticateUser(client, permissions);
|
|
|
|
return client;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates and authenticates a test user.
|
|
/// </summary>
|
|
/// <param name="client">The HTTP client to configure with auth.</param>
|
|
/// <param name="permissions">The permissions granted directly to the test user.</param>
|
|
/// <returns>The created user entity.</returns>
|
|
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions)
|
|
{
|
|
using IServiceScope scope = Services.CreateScope();
|
|
NemeraDbContext dbContext = scope.ServiceProvider.GetRequiredService<NemeraDbContext>();
|
|
|
|
// Create test user, with the permissions granted directly to it.
|
|
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
|
user.TotpSecret = null;
|
|
foreach (AuthorizationPermission permission in permissions)
|
|
user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id)));
|
|
|
|
dbContext.Users.Add(user);
|
|
await dbContext.SaveChangesAsync();
|
|
|
|
// Authenticate user.
|
|
LoginRequest loginRequest = _loginRequestFixture.Create(
|
|
username: user.Username,
|
|
password: "TestPass123!",
|
|
includeTotpCode: false
|
|
);
|
|
|
|
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
|
string content = await loginResponse.Content.ReadAsStringAsync();
|
|
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
|
|
|
// Set auth header for subsequent requests.
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
|
|
|
return user;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates an HTTP client with authentication headers and an admin test user with all permissions.
|
|
/// </summary>
|
|
/// <returns>An HTTP client configured with admin auth headers.</returns>
|
|
public async Task<HttpClient> CreateAuthenticatedAdminClientAsync()
|
|
{
|
|
HttpClient client = CreateClient();
|
|
TestUsername = $"testuser_{Guid.NewGuid()}";
|
|
|
|
// Add the X-Forwarded-For header.
|
|
client.DefaultRequestHeaders.Add("X-Forwarded-For",
|
|
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
|
|
|
// Create and authenticate admin user.
|
|
await CreateAndAuthenticateAdminUser(client);
|
|
|
|
return client;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates and authenticates an admin test user with all permissions.
|
|
/// </summary>
|
|
/// <param name="client">The HTTP client to configure with auth.</param>
|
|
/// <returns>The created user entity.</returns>
|
|
private async Task<UserEntity> CreateAndAuthenticateAdminUser(HttpClient client)
|
|
{
|
|
using IServiceScope scope = Services.CreateScope();
|
|
NemeraDbContext dbContext = scope.ServiceProvider.GetRequiredService<NemeraDbContext>();
|
|
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
|
|
|
// Create test user.
|
|
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
|
user.TotpSecret = null;
|
|
|
|
dbContext.Users.Add(user);
|
|
await dbContext.SaveChangesAsync();
|
|
|
|
// Set up admin permissions and roles.
|
|
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
|
await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
|
await dataSeedService.SetAdminRolePermissionsAsync(CancellationToken.None);
|
|
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
|
|
|
// Authenticate user.
|
|
LoginRequest loginRequest = _loginRequestFixture.Create(
|
|
username: user.Username,
|
|
password: "TestPass123!",
|
|
includeTotpCode: false
|
|
);
|
|
|
|
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
|
string content = await loginResponse.Content.ReadAsStringAsync();
|
|
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
|
|
|
// Set auth header for subsequent requests.
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
|
|
|
return user;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes the currently created test user from the database.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Test classes must call this in their per-test <c>DisposeAsync</c> instead of <see cref="Dispose"/>. The
|
|
/// factory is a shared <see cref="IClassFixture{TFixture}"/>, created once per test class and disposed by
|
|
/// xUnit only after all tests in the class have run. Calling <see cref="Dispose"/> from a per-test
|
|
/// <c>DisposeAsync</c> would dispose the web host and its service provider after the first test, making
|
|
/// every subsequent test in the class fail with an <see cref="ObjectDisposedException"/> when it resolves
|
|
/// services. <see cref="Dispose"/> is therefore reserved for xUnit's own class-teardown and must never be
|
|
/// invoked from a test.
|
|
/// </remarks>
|
|
/// <returns>A task representing the asynchronous operation.</returns>
|
|
public async Task RemoveTestUserAsync()
|
|
{
|
|
using IServiceScope scope = Services.CreateScope();
|
|
NemeraDbContext dbContext = scope.ServiceProvider.GetRequiredService<NemeraDbContext>();
|
|
|
|
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
|
if (user is not null)
|
|
{
|
|
dbContext.Users.Remove(user);
|
|
await dbContext.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes API factory resources.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Called by xUnit when the test class completes. Do not call from tests; per-test cleanup must use
|
|
/// <see cref="RemoveTestUserAsync"/>. See that method for the details.
|
|
/// </remarks>
|
|
public new void Dispose()
|
|
{
|
|
using IServiceScope scope = Services.CreateScope();
|
|
NemeraDbContext dbContext = scope.ServiceProvider.GetRequiredService<NemeraDbContext>();
|
|
|
|
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
|
if (user is not null)
|
|
{
|
|
dbContext.Users.Remove(user);
|
|
dbContext.SaveChanges();
|
|
}
|
|
|
|
base.Dispose();
|
|
}
|
|
}
|