Files
Heimdall/src/Heimdall.Web/Components/Pages/Login.razor
T
Arnaud Dartois 8195ee4ab8
Heimdall Gitea / Detect CI scope (pull_request) Successful in 4s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m32s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 8m36s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 11m34s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s
feat(auth): require initial administrator setup
2026-10-27 22:19:52 +01:00

235 lines
8.4 KiB
Plaintext

@page "/login"
@layout MudBlazorLayout
@inject HeimdallApiClient Api
@inject UiText Text
@inject AuthState Auth
@inject NavigationManager Navigation
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthStateProvider
@inject IJSRuntime JsRuntime
@inject Microsoft.Extensions.Logging.ILogger<Login> Logger
@using Microsoft.AspNetCore.WebUtilities
<div class="auth-page">
<div class="auth-card">
<div class="auth-header">
<div class="auth-icon">
<i class="fas fa-eye"></i>
</div>
<h1>Heimdall</h1>
<p>@Text["LoginPage_Subtitle"]</p>
</div>
<div class="auth-form">
<form @onsubmit="HandleSubmitAsync">
@if (!_requires2fa)
{
<MudTextField @bind-Value="_email"
Label="@Text["LoginPage_Email"]"
Variant="Variant.Outlined"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="email" />
<MudTextField @bind-Value="_password"
Label="@Text["LoginPage_Password"]"
Variant="Variant.Outlined"
InputType="InputType.Password"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="current-password" />
}
else
{
<MudAlert Severity="Severity.Info" Class="mb-4">
@Text["LoginPage_TwoFactorPrompt"]
</MudAlert>
<MudTextField @bind-Value="_twoFactorCode"
Label="@Text["LoginPage_TwoFactorCode"]"
Variant="Variant.Outlined"
Class="mb-4"
Required="true"
Immediate="true"
Autocomplete="one-time-code" />
}
<div class="auth-error">
@if (!string.IsNullOrEmpty(_errorMessage))
{
<MudAlert Severity="Severity.Error">@_errorMessage</MudAlert>
}
</div>
<MudButton Variant="Variant.Filled"
Color="Color.Primary"
FullWidth="true"
ButtonType="ButtonType.Submit"
Disabled="@_loading"
Class="auth-submit-btn">
@if (_loading)
{
<MudProgressCircular Size="Size.Small" Class="mr-2" Color="Color.Inherit" />
}
@(_loading ? Text["LoginPage_Loading"] : (_requires2fa ? Text["LoginPage_Verify"] : Text["LoginPage_SignIn"]))
</MudButton>
</form>
</div>
</div>
</div>
@code {
private string _challengeId = "";
private string _email = "";
private string _password = "";
private string _twoFactorCode = "";
private bool _requires2fa;
private bool _loading;
private string _errorMessage = "";
private string _returnUrl = "/dashboard";
private Task HandleSubmitAsync() =>
_requires2fa ? Verify2faAsync() : LoginAsync();
protected override async Task OnInitializedAsync()
{
Logger.LogInformation("Login page initialized. User logged in: {IsLoggedIn}", Auth.IsLoggedIn);
if (Auth.IsLoggedIn)
{
Logger.LogInformation("User already logged in, redirecting to dashboard");
Navigation.NavigateTo("/dashboard");
return;
}
try
{
if (await Api.IsAdminSetupRequiredAsync())
{
Navigation.NavigateTo("/setup", replace: true);
return;
}
}
catch (Exception ex) { Logger.LogWarning(ex, "Unable to load initial administrator setup status"); }
// Extract returnUrl from query string (validate local/relative only)
var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
var query = QueryHelpers.ParseQuery(uri.Query);
if (query.TryGetValue("returnUrl", out var returnUrl))
{
var raw = returnUrl.FirstOrDefault() ?? "/dashboard";
if (raw.StartsWith('/') && !raw.StartsWith("//") && !raw.Contains("://", StringComparison.Ordinal))
{
_returnUrl = raw;
Logger.LogInformation("Return URL extracted: {ReturnUrl}", _returnUrl);
}
}
}
private async Task LoginAsync()
{
_loading = true;
_errorMessage = "";
Logger.LogInformation("Login attempt for email: {Email}", _email);
try
{
var result = await Api.LoginAsync(_email, _password);
if (result is null)
{
Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email);
_errorMessage = Text["LoginPage_InvalidCredentials"];
return;
}
Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa);
// Check if 2FA is required
if (result.Requires2fa)
{
_challengeId = result.ChallengeId ?? "";
_password = "";
_requires2fa = true;
_loading = false;
Logger.LogInformation("2FA required for {Email}", _email);
return;
}
await CompleteAuthAsync(result);
}
catch (Exception ex)
{
Logger.LogError(ex, "Login error for {Email}", _email);
_errorMessage = UiErrors.OperationFailed();
}
finally { _loading = false; }
}
private async Task Verify2faAsync()
{
if (string.IsNullOrWhiteSpace(_twoFactorCode))
{
Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email);
_errorMessage = Text["LoginPage_TwoFactorCodeRequired"];
return;
}
_loading = true;
_errorMessage = "";
Logger.LogInformation("2FA verification attempt for {Email}", _email);
try
{
var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim());
if (result is null)
{
Logger.LogWarning("2FA verification failed for {Email}", _email);
_errorMessage = Text["LoginPage_InvalidTwoFactorCode"];
return;
}
Logger.LogInformation("2FA verification successful for {Email}", _email);
await CompleteAuthAsync(result);
}
catch (Exception ex)
{
Logger.LogError(ex, "2FA verification error for {Email}", _email);
_errorMessage = UiErrors.OperationFailed();
}
finally { _loading = false; }
}
private async Task CompleteAuthAsync(AuthResponse result)
{
Logger.LogInformation("Completing authentication for {Email}", _email);
// Update Blazor-level auth state
await AuthStateProvider.NotifyLoginAsync(result);
// Create middleware-level auth cookie
var cookieOk = true;
if (!string.IsNullOrEmpty(result.AccessToken))
{
Logger.LogDebug("Creating auth cookie for {Email}", _email);
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
AuthHelper.CreateSignInPayload(result.AccessToken));
}
else
{
Logger.LogWarning("No access token in auth response for {Email}", _email);
}
if (!cookieOk)
{
Logger.LogError("Failed to create auth cookie for {Email}", _email);
_errorMessage = Text["LoginPage_AuthSessionFailed"];
return;
}
Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl);
Snackbar.Add(Text["LoginPage_SignInSucceeded"], Severity.Success);
Navigation.NavigateTo(_returnUrl);
}
}