SPB Git

Repository Public

api.js 3.6 KB 97 lines javascript

1// Client de l'API du Dashboard : jeton CSRF (en mémoire seulement), relance après 403 csrf_failed,2// ré-authentification par clé d'accès après 401 reauth_required, retour à la connexion après 401 not_authenticated.34export class ApiError extends Error {5  constructor(status, code, message, retryAfter = null) {6    super(message);7    this.name = "ApiError";8    this.status = status;9    this.code = code;10    this.retryAfter = retryAfter;11  }12}1314let csrf = null;15let onAuthLost = () => {};16let reauthHandler = null;1718export function setCsrf(token) { csrf = token || null; }19export function setAuthLostHandler(fn) { onAuthLost = fn; }20export function setReauthHandler(fn) { reauthHandler = fn; }2122export async function send(method, path, body) {23  const headers = { Accept: "application/json" };24  if (body !== undefined) headers["Content-Type"] = "application/json";25  if (method !== "GET" && csrf) headers["X-CSRF-Token"] = csrf;26  let res;27  try {28    res = await fetch(path, {29      method, headers, credentials: "same-origin", cache: "no-store",30      body: body === undefined ? undefined : JSON.stringify(body),31    });32  } catch {33    throw new ApiError(0, "network_error", "Connexion au serveur impossible. Vérifiez le réseau, puis réessayez.");34  }35  let data = null;36  try { data = await res.json(); } catch { /* corps vide ou non JSON */ }37  if (!res.ok) {38    const e = (data && data.error) || {};39    const retry = Number(res.headers.get("Retry-After"));40    throw new ApiError(res.status, e.code || "http_error", e.message || `Erreur ${res.status}`, Number.isFinite(retry) && retry > 0 ? retry : null);41  }42  return data;43}4445/** GET /admin/api/session ; mémorise le jeton CSRF (renouvelé à chaque appel par le serveur). */46export async function refreshSession() {47  const session = await send("GET", "/admin/api/session");48  csrf = session.authenticated ? session.csrf_token : null;49  return session;50}5152export async function api(method, path, body) {53  let csrfRetried = false;54  let reauthDone = false;55  for (;;) {56    try {57      return await send(method, path, body);58    } catch (err) {59      if (!(err instanceof ApiError)) throw err;60      if (err.code === "csrf_failed" && !csrfRetried) {61        csrfRetried = true;62        const session = await refreshSession();63        if (session.authenticated) continue;64        onAuthLost();65        throw new ApiError(401, "not_authenticated", "Session expirée.");66      }67      if (err.code === "reauth_required" && !reauthDone && reauthHandler) {68        reauthDone = true;69        await reauthHandler(); // lève reauth_cancelled si l'administrateur renonce70        continue;71      }72      if (err.status === 401 && err.code === "not_authenticated") onAuthLost();73      throw err;74    }75  }76}7778export const get = (path) => api("GET", path);79export const post = (path, body) => api("POST", path, body === undefined ? {} : body);80export const patch = (path, body) => api("PATCH", path, body);81export const del = (path) => api("DELETE", path);8283/** Message affichable pour une erreur quelconque. */84export function errorMessage(err) {85  if (err instanceof ApiError) {86    if (err.code === "too_many_attempts") {87      const wait = err.retryAfter ? ` Réessayez dans ${Math.ceil(err.retryAfter / 60)} min.` : " Réessayez plus tard.";88      return `Trop de tentatives depuis cette adresse.${wait}`;89    }90    if (err.code === "bad_origin") return "Requête refusée : ouvrez le Dashboard à son adresse officielle.";91    return err.message;92  }93  return "Une erreur inattendue est survenue.";94}9596export const isSilent = (err) => err instanceof ApiError && (err.code === "reauth_cancelled" || err.code === "not_authenticated");97
Files main
Menu

Theme