using System.Security.Claims; using FozFc.Api.Api.Extensions; using FozFc.Api.Application.Common; using FozFc.Api.Domain; namespace FozFc.Api.Api.Authorization; /// Access-control guards shared by the endpoints (throw on denial). public static class EndpointGuards { public static string RequireUid(ClaimsPrincipal user) => user.GetUid() ?? throw ApiException.Unauthorized("Authentication required."); public static void RequireSelfOrAdmin(ClaimsPrincipal user, string uid) { var current = RequireUid(user); if (current != uid && !user.IsAdmin()) throw ApiException.Forbidden("You may only access your own account."); } /// Enforces the read/write policy for a generic collection. public static void RequireCollectionAccess(ClaimsPrincipal user, string collection, bool isWrite) { if (Collections.AdminOnly.Contains(collection)) { if (!user.IsAuthenticated()) throw ApiException.Unauthorized("Authentication required."); if (!user.IsAdmin()) throw ApiException.Forbidden("Admin access required."); return; } var isPublic = isWrite ? Collections.PublicWrite.Contains(collection) : Collections.PublicRead.Contains(collection); if (isPublic) return; if (!user.IsAuthenticated()) throw ApiException.Unauthorized("Authentication required."); } }