blazing-console/Components/RequiresAuth.razor
2024-12-23 15:37:42 -05:00

58 lines
No EOL
1.4 KiB
Text

@using Blazored.LocalStorage
@inject ILocalStorageService localStorage
@inject APIService api
@inject NavigationManager Navigation
@if (IsReady) {
@if (IsAuthenticated) {
@ChildContent
} else {
<FluentLayout>
<FluentHeader>
Blazing Console
</FluentHeader>
<FluentBodyContent>
<h1>Log in first</h1>
<FluentButton Appearance="@Appearance.Accent" OnClick="LoginButtonClicked">Log in</FluentButton>
</FluentBodyContent>
</FluentLayout>
}
} else {
@if (LoadingContent != null) {
@LoadingContent
} else {
<FluentProgressRing></FluentProgressRing>
}
}
@code {
public bool IsReady { get; set; } = false;
public bool IsAuthenticated { get; set; } = false;
protected override async Task OnInitializedAsync()
{
string? jwt = await localStorage.GetItemAsync<string>("jwt");
if (jwt == null) {
IsAuthenticated = false;
IsReady = true;
return;
}
api.SetJwt(jwt);
bool authorized = await api.TestAuthorization();
IsAuthenticated = authorized;
IsReady = true;
}
public void LoginButtonClicked() {
Navigation.NavigateTo("/login", false);
}
[Parameter]
public required RenderFragment ChildContent { get; set; }
[Parameter]
public RenderFragment? LoadingContent { get; set; }
}