SharpRSS/SharpRSS.Blazor/Auth/LocalStorageSessionStateProvider.cs

40 lines
1.5 KiB
C#
Raw Normal View History

using Blazored.LocalStorage;
using DotBased;
using DotBased.ASP.Auth;
using DotBased.Extensions;
using DotBased.Logging;
using Serilog;
using ILogger = DotBased.Logging.ILogger;
namespace SharpRSS.Blazor.Auth;
public class LocalStorageSessionStateProvider : ISessionStateProvider
{
public LocalStorageSessionStateProvider(ILocalStorageService localStorage)
{
_localStorage = localStorage;
_logger = LogService.RegisterLogger(typeof(LocalStorageSessionStateProvider));
}
private readonly ILocalStorageService _localStorage;
private readonly ILogger _logger;
public async Task<Result<string>> GetSessionStateAsync()
{
var localStorageValue = await _localStorage.GetItemAsync<string>(ISessionStateProvider.SessionStateName);
if (localStorageValue != null && !localStorageValue.IsNullOrWhiteSpace())
return Result<string>.Ok(localStorageValue);
_logger.Warning("Failed to get session token from local storage!");
return Result<string>.Failed("Local storage returned null or empty on session token.");
}
public async Task<Result> SetSessionStateAsync(string state)
{
if (state.IsNullOrWhiteSpace())
{
Log.Warning("Tried to save empty or null session state to local storage!");
return Result.Failed("Could not set session state to local storage, value is empty or null!");
}
await _localStorage.SetItemAsync(ISessionStateProvider.SessionStateName, state);
return Result.Ok();
}
}