bulletboards/ImageBoardServerApp/Auth/CustomAuthenticationStateProvider.cs
limited_dev ce201207d4 NOTE: temp commit, started rolling back changes to auth system
Signed-off-by: limited_dev <loginakkisativ@gmail.com>
2023-06-12 20:46:44 +02:00

63 lines
No EOL
2.3 KiB
C#

using System.Security.Claims;
using ImageBoardServerApp.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
namespace ImageBoardServerApp.Auth;
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ProtectedLocalStorage _sessionStorage;
private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
public CustomAuthenticationStateProvider(ProtectedLocalStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var userSessionStorageResult = await _sessionStorage.GetAsync<UserData>("UserSession");
var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null;
if (userSession == null)
return await Task.FromResult(new AuthenticationState(_anonymous));
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
//new Claim(ClaimTypes.Email, userSession.Email),
new Claim(ClaimTypes.Name, userSession.Email),
new Claim(ClaimTypes.Role, userSession.Role)
}, "CustomAuth"));
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
catch
{
Console.WriteLine("Resorting to Anon");
return await Task.FromResult(new AuthenticationState(_anonymous));
}
}
public async Task UpdateAuthenticationStateAsync(UserData session)
{
ClaimsPrincipal claimsPrincipal;
if (session != null)
{
await _sessionStorage.SetAsync("UserSession", session);
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name, session.Email),
new Claim(ClaimTypes.Role, session.Role)
}));
}
else
{
await _sessionStorage.DeleteAsync("UserSession");
claimsPrincipal = _anonymous;
}
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
}