using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using Heimdall.IntegrationTests.Factories; namespace Heimdall.IntegrationTests.Controllers; public static class TestHelpers { private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; /// /// Register a new admin user and return an authenticated HttpClient. /// Uses the test-only register-admin endpoint. /// /// /// Bootstrap an admin user and return an authenticated HttpClient. /// First user registered becomes Admin automatically. /// Also enables the auth.public-registration.enabled flag so viewer users can be created. /// public static async Task CreateAdminClientAsync(this HeimdallWebApplicationFactory factory) { var email = $"admin-{Guid.NewGuid()}@heimdall.test"; var client = factory.CreateClient(); // Le premier utilisateur enregistré devient automatiquement Admin var response = await client.PostAsJsonAsync("api/auth/register", new { email, password = "TestAdminPwd123!", displayName = "Test Admin" }); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadFromJsonAsync(Json); var token = content.GetProperty("accessToken").GetString()!; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // Activer les feature flags pour les autres tests await EnableSetting(client, "auth.public-registration.enabled", "true"); await EnableSetting(client, "auth.admin-registration.enabled", "true"); return client; } private static async Task EnableSetting(HttpClient client, string key, string value) { var response = await client.PostAsJsonAsync("api/settings", new { key, value, valueType = "bool", category = "Auth", description = key }); if (!response.IsSuccessStatusCode) { // La setting existe peut-être déjà — essayer PUT response = await client.PutAsJsonAsync($"api/settings/{key}", new { value, valueType = "bool" }); } } /// /// Bootstrap a viewer-authenticated HttpClient (second registered user, /// default role = Viewer). Requires an admin to have been created first /// (which enables public registration). /// public static async Task CreateViewerClientAsync(this HeimdallWebApplicationFactory factory) { // Bootstrap an admin first: the FIRST registered user becomes Admin. // Without this, the "viewer" below would become the first user (Admin), // which breaks role-based assertions. await CreateAdminClientAsync(factory); var email = $"viewer-{Guid.NewGuid()}@heimdall.test"; var client = factory.CreateClient(); var response = await client.PostAsJsonAsync("api/auth/register", new { email, password = "ViewerPwd123!", displayName = "Test Viewer" }); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadFromJsonAsync(Json); var token = content.GetProperty("accessToken").GetString()!; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); return client; } }