@page "/login" @inject IAuthService AuthService @inject CustomAuthStateProvider AuthStateProvider @inject NavigationManager Navigation @inject ISettingsService SettingsService @inject ILocalizationService Loc @rendermode InteractiveServer @Loc["page.title.login"]

@Loc["login.heading"]

@if (!show2FA) {
@Loc["login.link.register"]
} else {

@Loc["login.2fa.instruction"]

} @if (!string.IsNullOrEmpty(errorMessage)) {
@errorMessage
}
@code { private string username = string.Empty; private string password = string.Empty; private string twoFactorCode = string.Empty; private string errorMessage = string.Empty; private bool isBusy; private bool show2FA; protected override async Task OnInitializedAsync() { if (AuthService.IsLoggedIn) { Navigation.NavigateTo("/"); return; } var users = await SettingsService.GetUsersAsync(); if (users.Count == 0) { Navigation.NavigateTo("/first-run-setup"); } } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender && AuthService.IsLoggedIn) Navigation.NavigateTo("/"); } private async Task HandleKeyDown(KeyboardEventArgs e) { if (e.Key == "Enter") { if (show2FA) await Verify2FA(); else await DoLogin(); } } private async Task DoLogin() { if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { errorMessage = Loc["login.error.empty_fields"]; return; } isBusy = true; errorMessage = string.Empty; try { var result = await AuthService.LoginAsync(username, password); if (AuthService.Is2FARequired) { show2FA = true; password = string.Empty; } else if (result) { AuthStateProvider.NotifyStateChanged(); Navigation.NavigateTo("/"); } else { errorMessage = Loc["login.error.invalid_credentials"]; } } catch (Exception ex) { errorMessage = $"{Loc["common.error"]} {ex.Message}"; } finally { isBusy = false; } } private async Task Verify2FA() { if (string.IsNullOrWhiteSpace(twoFactorCode) || twoFactorCode.Length != 6) { errorMessage = Loc["login.2fa.error.invalid_code"]; return; } isBusy = true; errorMessage = string.Empty; try { var result = await AuthService.Verify2FAAsync(twoFactorCode); if (result) { AuthStateProvider.NotifyStateChanged(); Navigation.NavigateTo("/"); } else { errorMessage = Loc["login.2fa.error.code_failed"]; } } catch (Exception ex) { errorMessage = $"{Loc["common.error"]} {ex.Message}"; } finally { isBusy = false; } } }