using System.Text.Json;
using JdeScoping.Core.Models.Auth;
using Microsoft.JSInterop;
namespace JdeScoping.Client.Auth;
///
/// Stores user info in browser sessionStorage via JS interop.
/// Uses sessionStorage (not localStorage) so it clears on browser close,
/// matching cookie session behavior.
///
public class UserStorageService : IUserStorageService
{
private const string UserKey = "jdescoping_user";
private readonly IJSRuntime _jsRuntime;
public UserStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task GetUserAsync()
{
try
{
var json = await _jsRuntime.InvokeAsync("jdeScopingInterop.getSessionStorage", UserKey);
if (string.IsNullOrEmpty(json))
{
return null;
}
return JsonSerializer.Deserialize(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
catch
{
return null;
}
}
public async Task SetUserAsync(UserInfoDto user)
{
var json = JsonSerializer.Serialize(user);
await _jsRuntime.InvokeVoidAsync("jdeScopingInterop.setSessionStorage", UserKey, json);
}
public async Task RemoveUserAsync()
{
await _jsRuntime.InvokeVoidAsync("jdeScopingInterop.removeSessionStorage", UserKey);
}
}