Files
Heimdall/src/Heimdall.Web/Services/AuthState.cs
T

140 lines
5.9 KiB
C#
Raw Normal View History

using System.Security.Claims;
using System.Text.Json.Serialization;
using Heimdall.Infrastructure.Security;
namespace Heimdall.Web.Services;
public class AuthState
{
/// <summary>Nom du cookie d'authentification ASP.NET Core (schéma Cookies).</summary>
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;
/// <summary>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.</summary>
public string? AuthCookie { get; set; }
/// <summary>Resolved permission claims from the user's roles.</summary>
public IReadOnlySet<string> Permissions { get; private set; } = new HashSet<string>();
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?.Permissions?.ToHashSet(StringComparer.Ordinal)
?? response.User?.Roles?.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
.ToHashSet(StringComparer.Ordinal)
?? new HashSet<string>(StringComparer.Ordinal);
}
/// <summary>
/// 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.
/// </summary>
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;
var permissions = principal.FindAll("permission").Select(c => c.Value).Distinct(StringComparer.Ordinal).ToList();
User = new UserInfo(id, email, displayName, roles, permissions);
Permissions = permissions.ToHashSet(StringComparer.Ordinal);
}
public void Logout()
{
AccessToken = null;
RefreshToken = null;
User = null;
AuthCookie = null;
Permissions = new HashSet<string>();
}
}
// ─── 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<string>? Roles,
[property: JsonPropertyName("permissions")] IList<string>? Permissions = null);
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<string>? Roles { get; set; }
public IList<Guid>? 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<T>(
[property: JsonPropertyName("items")] IReadOnlyList<T> Items,
[property: JsonPropertyName("totalCount")] int TotalCount,
[property: JsonPropertyName("page")] int Page,
[property: JsonPropertyName("pageSize")] int PageSize);