u
This commit is contained in:
53
src/FrontOffice.Main/Utilities/AuthService.cs
Normal file
53
src/FrontOffice.Main/Utilities/AuthService.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using Blazored.LocalStorage;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
|
||||
namespace FrontOffice.Main.Utilities;
|
||||
|
||||
public class AuthService
|
||||
{
|
||||
private readonly ILocalStorageService _localStorage;
|
||||
private readonly NavigationManager _navigation;
|
||||
private readonly ISnackbar _snackbar;
|
||||
|
||||
private const string TokenStorageKey = "auth:token";
|
||||
|
||||
public AuthService(ILocalStorageService localStorage, NavigationManager navigation, ISnackbar snackbar)
|
||||
{
|
||||
_localStorage = localStorage;
|
||||
_navigation = navigation;
|
||||
_snackbar = snackbar;
|
||||
}
|
||||
|
||||
public async Task<bool> IsAuthenticatedAsync()
|
||||
{
|
||||
var token = await _localStorage.GetItemAsync<string>(TokenStorageKey);
|
||||
return !string.IsNullOrWhiteSpace(token);
|
||||
}
|
||||
|
||||
public async Task<string?> GetTokenAsync()
|
||||
{
|
||||
return await _localStorage.GetItemAsync<string>(TokenStorageKey);
|
||||
}
|
||||
|
||||
public async Task LogoutAsync()
|
||||
{
|
||||
await _localStorage.RemoveItemAsync(TokenStorageKey);
|
||||
await _localStorage.RemoveItemAsync("auth:phone-number");
|
||||
await _localStorage.RemoveItemAsync("auth:redirect");
|
||||
await _localStorage.RemoveItemAsync("referral:code");
|
||||
|
||||
_snackbar.Add("با موفقیت از حساب کاربری خارج شدید.", Severity.Success);
|
||||
_navigation.NavigateTo(RouteConstants.Main.MainPage);
|
||||
}
|
||||
|
||||
public async Task RequireAuthenticationAsync()
|
||||
{
|
||||
var isAuthenticated = await IsAuthenticatedAsync();
|
||||
if (!isAuthenticated)
|
||||
{
|
||||
_snackbar.Add("لطفاً ابتدا وارد حساب کاربری شوید.", Severity.Warning);
|
||||
_navigation.NavigateTo(RouteConstants.Main.MainPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user