Files
FoodsharingOnboarding/FoodsharingSiegen.Server/Auth/TokenAuthStateProvider.cs
Andre Beging 5026196b46 Claim Logic
2022-04-11 15:51:11 +02:00

92 lines
3.4 KiB
C#

using System.Security.Claims;
using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Server.Auth;
using FoodsharingSiegen.Server.Data.Service;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components.Authorization;
namespace FoodsharingSiegen.Server.Service
{
/// <summary>
/// The token auth state provider class (a. beging, 02.04.2022)
/// </summary>
/// <seealso cref="AuthenticationStateProvider"/>
public class TokenAuthStateProvider : AuthenticationStateProvider
{
#region Private Fields
/// <summary> LocalStorageService </summary>
private readonly LocalStorageService _localStorageService;
private readonly UserService _userService;
#endregion
#region Setup/Teardown
/// <summary>
/// Constructor
/// </summary>
/// <param name="localStorageService"></param>
/// <param name="userService"></param>
public TokenAuthStateProvider(LocalStorageService localStorageService, UserService userService)
{
_localStorageService = localStorageService;
_userService = userService;
}
#endregion
#region Override GetAuthenticationStateAsync
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Get the current authenticationstate </summary>
/// <remarks> A. Beging, 02.02.2022. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var token = await _localStorageService.GetItem<string>(StorageKeys.TokenKey);
var tokenValid = AuthHelper.ValidateToken(token, out var user);
var checkR = await _userService.CheckForceLogout(user);
if (checkR.Success && checkR.Data)
tokenValid = false;
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
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Mark user as authenticated. </summary>
/// <remarks> A. Beging, 02.02.2022. </remarks>
////////////////////////////////////////////////////////////////////////////////////////////////////
public void MarkUserAsAuthenticated() => NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
#endregion
#region Public Method MarkUserAsLoggedOut
/// <summary>
/// Marks the user as logged out (a. beging, 02.04.2022)
/// </summary>
public void MarkUserAsLoggedOut()
{
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
var authState = Task.FromResult(new AuthenticationState(anonymousUser));
NotifyAuthenticationStateChanged(authState);
}
#endregion
}
}