| | | 1 | | using Microsoft.JSInterop; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using Microsoft.AspNetCore.Components.Authorization; |
| | | 4 | | |
| | | 5 | | namespace Syki.Front.Auth; |
| | | 6 | | |
| | 976 | 7 | | public class SykiAuthStateProvider(ILocalStorageService storage) : AuthenticationStateProvider |
| | | 8 | | { |
| | | 9 | | public override async Task<AuthenticationState> GetAuthenticationStateAsync() |
| | | 10 | | { |
| | 948 | 11 | | var user = await storage.GetItemAsync<GetUserAccountOut>("User"); |
| | | 12 | | |
| | 948 | 13 | | if (user == null) |
| | | 14 | | { |
| | 0 | 15 | | return new(new ClaimsPrincipal(new ClaimsIdentity())); |
| | | 16 | | } |
| | | 17 | | |
| | 948 | 18 | | return new(CreateClaimsPrincipalFromToken(user)); |
| | 948 | 19 | | } |
| | | 20 | | |
| | | 21 | | public void MarkUserAsAuthenticated() |
| | | 22 | | { |
| | 948 | 23 | | NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); |
| | 948 | 24 | | } |
| | | 25 | | |
| | | 26 | | public void MarkUserAsLoggedOut() |
| | | 27 | | { |
| | 0 | 28 | | NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | private static ClaimsPrincipal CreateClaimsPrincipalFromToken(GetUserAccountOut user) |
| | | 32 | | { |
| | 948 | 33 | | var identity = new ClaimsIdentity("Bearer"); |
| | | 34 | | |
| | 948 | 35 | | identity.AddClaim(new Claim("sub", user.Id.ToString())); |
| | 948 | 36 | | identity.AddClaim(new Claim("name", user.Name)); |
| | 948 | 37 | | identity.AddClaim(new Claim("email", user.Email)); |
| | 948 | 38 | | identity.AddClaim(new Claim("role", user.Role.ToString())); |
| | 948 | 39 | | identity.AddClaim(new Claim(ClaimTypes.Role, user.Role.ToString())); |
| | | 40 | | |
| | 948 | 41 | | return new(identity); |
| | | 42 | | } |
| | | 43 | | } |