/** * Trouve-KA — client API admin (jeton X-Admin-Token, gestion 401) * Author: Simon-Pierre Boucher * Contact: contact@spboucher.ai */ /** Clé sessionStorage où le jeton admin est conservé (session seulement). */ export const ADMIN_TOKEN_KEY = "trouveka-admin-token"; /** Levée quand le backend répond 401/403 : le jeton doit être redemandé. */ export class UnauthorizedError extends Error { constructor() { super("Jeton d'administration invalide ou expiré"); this.name = "UnauthorizedError"; } } /** * Fetch authentifié vers l'API admin (chemins relatifs `/api/admin/...`). * Ajoute le header `X-Admin-Token` et convertit 401/403 en UnauthorizedError. */ export async function adminFetch( path: string, token: string, init?: RequestInit, ): Promise { const headers: Record = { "X-Admin-Token": token, ...(init?.body ? { "Content-Type": "application/json" } : {}), }; const res = await fetch(path, { ...init, headers }); if (res.status === 401 || res.status === 403) { throw new UnauthorizedError(); } if (!res.ok) { throw new Error(`Erreur ${res.status}`); } return (await res.json()) as T; }