using Blazored.LocalStorage; using decePubClient.Helpers; using decePubClient.Models; using Microsoft.AspNetCore.Components.Authorization; using System.Security.Claims; using System.Text.Json; namespace decePubClient.Services { public class TokenAuthStateProvider(ILocalStorageService storage, IStorage dbStorage, ILogger logger) : AuthenticationStateProvider { public void SetToken(/*string token, long expirationTicks = default*/) { //AuthData = await Storage.GetItemAsync(nameof(AuthData)); //if (string.IsNullOrEmpty(token)) //{ // Logger.LogInformation($"set null({nameof(SetToken)})"); // AuthData.Token = null; // AuthData.TokenExpiration = null; //} //else //{ // AuthData.Token = token; // AuthData.TokenExpiration = expirationTicks; //} //await Storage.SetItemAsync(nameof(AuthData), AuthData); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } /// The stored token while it is still valid, otherwise null. public async Task GetToken(CancellationToken cancellationToken = default) { var authData = await storage.GetItemAsync(nameof(AuthData), cancellationToken); if (string.IsNullOrEmpty(authData?.Token) || authData.TokenExpiration is not { } expiration || expiration <= DateTime.UtcNow.Ticks) return null; return authData.Token; } public async Task IsAuthenticatedAsync(CancellationToken cancellationToken = default) => await GetToken(cancellationToken) is not null; public async Task LogoutAsync(bool deleteDb = false, CancellationToken cancellationToken = default) { logger.LogInformation($"set null({nameof(LogoutAsync)})"); //await Storage.RemoveItemAsync(nameof(PrivateCacheData)); await storage.RemoveItemAsync(nameof(AuthData), cancellationToken); if (deleteDb) await dbStorage.RemoveAll(includeClientLogs: true, cancellationToken: cancellationToken); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public override async Task GetAuthenticationStateAsync() { var authData = await storage.GetItemAsync(nameof(AuthData)); if (string.IsNullOrEmpty(authData?.Token)) { logger.LogInformation($"set null({nameof(GetAuthenticationStateAsync)})"); return new(new()); } var claims = new List { new(ClaimTypes.UserData, JsonSerializer.Serialize(authData.User, SUtility.DefaultSerializer)) }; //claims.Add(new(Policies.IsUser, (AuthData.User.Policies.Contains(Policies.IsUser)).ToString().ToLower())); //claims.Add(new(Policies.UserPlus, (AuthData.User.Policies.Contains(Policies.UserPlus)).ToString().ToLower())); //claims.Add(new(Policies.IsAdmin, (AuthData.User.Policies.Contains(Policies.IsAdmin)).ToString().ToLower())); var identity = new ClaimsIdentity(claims, "jwt"); return new(new(identity)); } } }