using System.Security.Claims;
using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Server.Auth;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components.Authorization;
namespace FoodsharingSiegen.Server.Service
{
///
/// The token auth state provider class (a. beging, 02.04.2022)
///
///
public class TokenAuthStateProvider : AuthenticationStateProvider
{
#region Private Fields
/// LocalStorageService
private readonly LocalStorageService _localStorageService;
#endregion
#region Setup/Teardown
///
/// Constructor
///
///
public TokenAuthStateProvider(LocalStorageService localStorageService) => _localStorageService = localStorageService;
#endregion
#region Override GetAuthenticationStateAsync
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Get the current authenticationstate
/// A. Beging, 02.02.2022.
////////////////////////////////////////////////////////////////////////////////////////////////////
public override async Task GetAuthenticationStateAsync()
{
var token = await _localStorageService.GetItem(StorageKeys.TokenKey);
var tokenValid = await AuthHelper.ValidateToken(token);
var identity = new ClaimsIdentity();
if (tokenValid)
identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "user")
}, "TODO");
var claimsPrincipal = new ClaimsPrincipal(identity);
return new AuthenticationState(claimsPrincipal);
}
#endregion
#region Public Method MarkUserAsAuthenticated
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Mark user as authenticated.
/// A. Beging, 02.02.2022.
////////////////////////////////////////////////////////////////////////////////////////////////////
public void MarkUserAsAuthenticated() => NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
#endregion
#region Public Method MarkUserAsLoggedOut
///
/// Marks the user as logged out (a. beging, 02.04.2022)
///
public void MarkUserAsLoggedOut()
{
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
var authState = Task.FromResult(new AuthenticationState(anonymousUser));
NotifyAuthenticationStateChanged(authState);
}
#endregion
}
}