Files
Heimdall/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs
T
arnaud.dartois 622add46ad
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Failing after 4m5s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 1s
refactor(identity): isolate ASP.NET Identity in Infrastructure
2026-11-04 11:37:53 +01:00

157 lines
6.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Net.Http.Json;
using Heimdall.Domain.Entities;
using Heimdall.TestCommon;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Playwright;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.E2E.Tests.Pages;
/// <summary>
/// Full authentication flow tests driven through the real Blazor UI:
/// login success/failure, validation, logout, protected-route redirects
/// and the one-time administrator setup gate.
/// </summary>
[Collection("E2E")]
public class AuthFlowTests : E2ETestBase
{
public AuthFlowTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
[Fact]
public async Task Login_page_renders()
{
await Page.GotoAsync($"{BaseUrl}/login");
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
(await Page.Locator("h1").TextContentAsync())!.ShouldContain("Heimdall");
var regCount = await Page.Locator("a[href='/register']").CountAsync();
regCount.ShouldBe(0);
}
[Fact]
public async Task First_run_requires_setup_and_creates_the_initial_admin()
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
{
var deleted = await users.DeleteAsync(user);
deleted.Succeeded.ShouldBeTrue();
}
}
try
{
await Page.GotoAsync($"{BaseUrl}/login");
await Page.WaitForURLAsync("**/setup**", new() { Timeout = 15000 });
await GotoWithCircuitAsync("/setup");
await Page.FillAsync("input[autocomplete='name']", "Initial Admin");
await Page.FillAsync("input[autocomplete='email']", $"bootstrap-{Guid.NewGuid():N}@heimdall.test");
var passwordFields = Page.Locator("input[autocomplete='new-password']");
await passwordFields.Nth(0).FillAsync("FirstAdmin!Pass123456");
await passwordFields.Nth(1).FillAsync("FirstAdmin!Pass123456");
await Page.ClickAsync("button:has-text('Créer l’administrateur')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var status = await http.GetFromJsonAsync<BootstrapStatus>("/api/auth/bootstrap-status");
status!.SetupRequired.ShouldBeFalse();
}
finally
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
await users.DeleteAsync(user);
await Program.SeedAsync(App, App.Configuration);
}
}
[Fact]
public async Task Login_with_valid_admin_credentials_redirects_to_dashboard()
{
await LoginViaUiAsync();
// Blazor renders the dashboard content asynchronously after navigation.
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
(await Page.Locator("body").TextContentAsync())!.ShouldContain("Bienvenue");
// Nav bar should show the main items for an admin
var navCount = await Page.Locator("a[href='/users']").CountAsync();
navCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task Login_with_wrong_password_shows_error()
{
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", AdminEmail);
await Page.FillAsync("input[autocomplete='current-password']", "WrongPassword123!");
await Page.ClickAsync("button:has-text('Se connecter')");
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
Page.Url.ShouldContain("/login");
}
[Fact]
public async Task Login_with_unknown_email_shows_error()
{
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", "nobody@heimdall.test");
await Page.FillAsync("input[autocomplete='current-password']", AdminPassword);
await Page.ClickAsync("button:has-text('Se connecter')");
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
}
[Fact]
public async Task Protected_page_redirects_to_login_when_unauthenticated()
{
await Page.GotoAsync($"{BaseUrl}/users");
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task Logout_returns_to_login()
{
await LoginViaUiAsync();
// Logout is a MudMenuItem in the user menu
await Page.ClickAsync("text=Déconnexion").ContinueWith(_ => { });
// Fallback: navigate via the /_auth/signout endpoint if the button isn't present
if (Page.Url.Contains("/dashboard"))
{
await Page.EvaluateAsync("fetch('/_auth/signout', { method: 'POST' })");
await Page.GotoAsync($"{BaseUrl}/dashboard");
}
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task Register_route_redirects_to_login_after_initial_setup()
{
await Page.GotoAsync($"{BaseUrl}/register");
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task AnonymousRegistrationApi_route_is_not_available()
{
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var response = await http.PostAsJsonAsync("/api/auth/register", new
{
email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test",
password = "RegisterPass123!",
displayName = "E2E Register"
});
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
}
private sealed record BootstrapStatus(bool SetupRequired);
}