#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.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 Lumina.Presentation.Api.IntegrationTests.Common.Setup; // /// Factory that extends to provide authenticated HTTP clients for testing. /// [ExcludeFromCodeCoverage] public class AuthenticatedLuminaApiFactory : LuminaApiFactory, 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(); /// /// Gets the username of the currently created test user. /// public string? TestUsername { get; private set; } /// /// Creates an HTTP client with authentication headers and a test user. /// /// The permissions granted directly to the test user, if any. /// An HTTP client configured with auth headers. public async Task 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; } /// /// Creates and authenticates a test user. /// /// The HTTP client to configure with auth. /// The permissions granted directly to the test user. /// The created user entity. private async Task CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions) { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); // 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(content, _jsonOptions); // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; } /// /// Creates an HTTP client with authentication headers and an admin test user with all permissions. /// /// An HTTP client configured with admin auth headers. public async Task 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; } /// /// Creates and authenticates an admin test user with all permissions. /// /// The HTTP client to configure with auth. /// The created user entity. private async Task CreateAndAuthenticateAdminUser(HttpClient client) { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService(); // 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(user.Id, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRolePermissionsAsync(user.Id, 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(content, _jsonOptions); // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; } /// /// Removes the currently created test user from the database. /// /// /// Test classes must call this in their per-test DisposeAsync instead of . The /// factory is a shared , created once per test class and disposed by /// xUnit only after all tests in the class have run. Calling from a per-test /// DisposeAsync would dispose the web host and its service provider after the first test, making /// every subsequent test in the class fail with an when it resolves /// services. is therefore reserved for xUnit's own class-teardown and must never be /// invoked from a test. /// /// A task representing the asynchronous operation. public async Task RemoveTestUserAsync() { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername); if (user is not null) { dbContext.Users.Remove(user); await dbContext.SaveChangesAsync(); } } /// /// Disposes API factory resources. /// /// /// Called by xUnit when the test class completes. Do not call from tests; per-test cleanup must use /// . See that method for the details. /// public new void Dispose() { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername); if (user is not null) { dbContext.Users.Remove(user); dbContext.SaveChanges(); } base.Dispose(); } }