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