using Blazored.LocalStorage; using HeartTrack.Models.Authentification; using Microsoft.AspNetCore.Components.Authorization; using System.Security.Claims; namespace HeartTrack.Services.AuthentificationService { public class CustomStateProvider : AuthenticationStateProvider { private readonly IAuthService _authService; private readonly ILocalStorageService _localStorage; public CurrentUser? currentUser { get; set; } public CustomStateProvider(IAuthService authService, ILocalStorageService localStorage) { _authService = authService; _localStorage = localStorage; } public override async Task GetAuthenticationStateAsync() { await RehydrateUserStateAsync(); var identity = new ClaimsIdentity(); if (currentUser?.IsAuthenticated == true) { var claims = new[] { new Claim(ClaimTypes.Name, currentUser.UserName) } .Concat(currentUser.Claims.Select(c => new Claim(c.Key, c.Value))); identity = new ClaimsIdentity(claims, "Server authentication"); } return new AuthenticationState(new ClaimsPrincipal(identity)); } public async Task Login(LoginRequest loginParameters) { _authService.Login(loginParameters); var user = await _authService.GetUser(loginParameters.UserName, loginParameters.Password); currentUser = user; await _localStorage.SetItemAsync("currentUser", currentUser); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public async Task Logout() { await _localStorage.RemoveItemAsync("currentUser"); currentUser = null; NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } private async Task RehydrateUserStateAsync() { currentUser = await _localStorage.GetItemAsync("currentUser"); if (currentUser != null && currentUser.IsAuthenticated) { // Utilisateur authentifié } else { currentUser = new CurrentUser(); } } } }