64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using QuantEngine.Web.Client.Services;
|
|
|
|
namespace QuantEngine.Web.Client.Infrastructure
|
|
{
|
|
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
|
|
{
|
|
private readonly LocalStorageService _localStorage;
|
|
private readonly ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
|
|
private const string StorageKey = "quant_admin_session";
|
|
|
|
public CustomAuthenticationStateProvider(LocalStorageService localStorage)
|
|
{
|
|
_localStorage = localStorage;
|
|
}
|
|
|
|
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
try
|
|
{
|
|
var username = await _localStorage.GetAsync<string>(StorageKey);
|
|
if (!string.IsNullOrEmpty(username))
|
|
{
|
|
var identity = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, username),
|
|
new Claim(ClaimTypes.Role, "Admin")
|
|
}, "QuantAdminAuth");
|
|
|
|
var user = new ClaimsPrincipal(identity);
|
|
return new AuthenticationState(user);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Return anonymous if localStorage isn't ready
|
|
}
|
|
|
|
return new AuthenticationState(_anonymous);
|
|
}
|
|
|
|
public async Task MarkUserAsAuthenticatedAsync(string username)
|
|
{
|
|
await _localStorage.SetAsync(StorageKey, username);
|
|
|
|
var identity = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, username),
|
|
new Claim(ClaimTypes.Role, "Admin")
|
|
}, "QuantAdminAuth");
|
|
|
|
var user = new ClaimsPrincipal(identity);
|
|
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
|
|
}
|
|
|
|
public async Task MarkUserAsLoggedOutAsync()
|
|
{
|
|
await _localStorage.DeleteAsync(StorageKey);
|
|
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(_anonymous)));
|
|
}
|
|
}
|
|
}
|