blazing-console/Components/RequiresAuth.razor

59 lines
1.7 KiB
Text
Raw Normal View History

@*
* Copyright 2024 Ivy Collective <sys@ivycollective.dev>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*@
2024-12-23 15:37:42 -05:00
@using Blazored.LocalStorage
@inject ILocalStorageService localStorage
@inject APIService api
@inject NavigationManager Navigation
2024-12-23 18:41:17 -05:00
@if (IsAuthenticated) {
@ChildContent
2024-12-23 15:37:42 -05:00
} else {
@if (LoadingContent != null) {
@LoadingContent
} else {
<div style="display: flex; justify-content: center; align-items: center; min-height: 100vh;">
<FluentProgressRing Width="6rem"></FluentProgressRing>
</div>
2024-12-23 15:37:42 -05:00
}
}
@code {
public bool IsAuthenticated { get; set; } = false;
protected override async Task OnInitializedAsync()
{
string? jwt = await localStorage.GetItemAsync<string>("jwt");
if (jwt == null) {
2024-12-23 18:41:17 -05:00
Navigation.NavigateTo("/login", false);
2024-12-23 15:37:42 -05:00
return;
}
api.SetJwt(jwt);
bool authorized = await api.TestAuthorization();
2024-12-23 18:41:17 -05:00
if (authorized) {
IsAuthenticated = true;
} else {
Navigation.NavigateTo("/login", false);
}
2024-12-23 15:37:42 -05:00
}
[Parameter]
public required RenderFragment ChildContent { get; set; }
[Parameter]
public RenderFragment? LoadingContent { get; set; }
}