using System.Security.Claims; using System.Text.Json.Serialization; using Heimdall.Infrastructure.Security; namespace Heimdall.Web.Services; public class AuthState { /// Nom du cookie d'authentification ASP.NET Core (schéma Cookies). public const string AuthCookieName = ".Heimdall.Auth"; public SemaphoreSlim RefreshLock { get; } = new(1, 1); public string? AccessToken { get; set; } public string? RefreshToken { get; set; } public UserInfo? User { get; set; } public bool IsLoggedIn => User is not null; /// Valeur du cookie d'authentification, capturée lors de la restauration /// SSR (LoginFromPrincipal). Réutilisée par le client HTTP pour authentifier les /// appels du circuit Blazor quand aucun JWT n'est disponible (sessionStorage vide /// après F5/reload) — sinon ces appels partent sans auth et reçoivent 302. public string? AuthCookie { get; set; } /// Resolved permission claims from the user's roles. public IReadOnlySet Permissions { get; private set; } = new HashSet(); public bool HasPermission(string permission) => Permissions.Contains(permission); public void Login(AuthResponse response) { AccessToken = response.AccessToken; RefreshToken = response.RefreshToken; User = response.User; // Le JWT prend le relais — ne pas conserver un cookie d'une session précédente AuthCookie = null; // Resolve permissions from roles (same mapping as JWT + cookie auth) Permissions = response.User?.Roles? .SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : []) .ToHashSet() ?? new HashSet(); } /// /// Restores a session from the middleware cookie principal (SSR / page /// reload). No JWT tokens are available in that path, but identity and /// roles are enough for authorization and rendering. /// public void LoginFromPrincipal(ClaimsPrincipal principal) { var idClaim = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (idClaim is null || !Guid.TryParse(idClaim, out var id)) { Logout(); return; } var email = principal.FindFirst(ClaimTypes.Email)?.Value ?? ""; var displayName = principal.FindFirst(ClaimTypes.Name)?.Value ?? email; var roles = principal.FindAll(ClaimTypes.Role).Select(c => c.Value).ToList(); AccessToken = null; RefreshToken = null; User = new UserInfo(id, email, displayName, roles); Permissions = roles .SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : []) .ToHashSet(); } public void Logout() { AccessToken = null; RefreshToken = null; User = null; AuthCookie = null; Permissions = new HashSet(); } } // ─── Response DTOs ──────────────────────────────────────────────── public record AuthResponse( [property: JsonPropertyName("accessToken")] string AccessToken, [property: JsonPropertyName("refreshToken")] string RefreshToken, [property: JsonPropertyName("expiresAt")] DateTime ExpiresAt, [property: JsonPropertyName("requires2fa")] bool Requires2fa, [property: JsonPropertyName("user")] UserInfo? User, [property: JsonPropertyName("challengeId")] string? ChallengeId = null); public record UserInfo( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("email")] string Email, [property: JsonPropertyName("displayName")] string DisplayName, [property: JsonPropertyName("roles")] IList? Roles); public record SiteItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("name")] string Name, [property: JsonPropertyName("address")] string? Address, [property: JsonPropertyName("timezone")] string Timezone, [property: JsonPropertyName("ntfyTopic")] string? NtfyTopic, [property: JsonPropertyName("enabled")] bool Enabled, [property: JsonPropertyName("autoUpdateEnabled")] bool AutoUpdateEnabled, [property: JsonPropertyName("createdAt")] DateTime CreatedAt); public record SiteWithTokenResult( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("name")] string Name, [property: JsonPropertyName("address")] string? Address, [property: JsonPropertyName("timezone")] string Timezone, [property: JsonPropertyName("registrationToken")] string? RegistrationToken, [property: JsonPropertyName("tokenExpiresAt")] DateTime? TokenExpiresAt); public class UserItem { public Guid Id { get; set; } public string Email { get; set; } = ""; public string DisplayName { get; set; } = ""; public string? Theme { get; set; } public string Language { get; set; } = "fr"; public IList? Roles { get; set; } public IList? SiteIds { get; set; } public bool TwoFactorEnabled { get; set; } public bool IsLockedOut { get; set; } public DateTime? LockoutEnd { get; set; } public int AccessFailedCount { get; set; } public bool EmailConfirmed { get; set; } public DateTime CreatedAt { get; set; } } public record PasswordResetResult( [property: JsonPropertyName("temporaryPassword")] string TemporaryPassword); public record PagedData( [property: JsonPropertyName("items")] IReadOnlyList Items, [property: JsonPropertyName("totalCount")] int TotalCount, [property: JsonPropertyName("page")] int Page, [property: JsonPropertyName("pageSize")] int PageSize);