File size: 1,613 Bytes
6cc3d86
 
982bad4
 
 
 
 
 
 
 
 
 
2298ff2
 
 
6cc3d86
2298ff2
 
 
 
 
 
 
 
 
6cc3d86
 
 
 
 
 
 
 
 
982bad4
6cc3d86
982bad4
6cc3d86
982bad4
6cc3d86
 
 
982bad4
 
6cc3d86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const API = "";

/** Stored when cookie-based session is unavailable (e.g. HF Space proxy). */
const AUTH_TOKEN_KEY = "web_ui_auth_token";

export function apiFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
  const headers = new Headers(init.headers);
  const token = sessionStorage.getItem(AUTH_TOKEN_KEY);
  if (token) headers.set("Authorization", `Bearer ${token}`);
  return fetch(input, { ...init, credentials: "include", headers });
}

const ME_TIMEOUT_MS = 15_000;

/** Session check; sends Bearer token when present (HF Space / no cookie). Aborts if the server never responds. */
export async function fetchMe(): Promise<{ authenticated: boolean }> {
  const c = new AbortController();
  const id = setTimeout(() => c.abort(), ME_TIMEOUT_MS);
  try {
    const r = await apiFetch(`${API}/api/me`, { signal: c.signal });
    if (!r.ok) throw new Error("me failed");
    return r.json();
  } finally {
    clearTimeout(id);
  }
}

export async function login(password: string): Promise<void> {
  const r = await fetch(`${API}/api/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({ password }),
  });
  const j = (await r.json().catch(() => ({}))) as { detail?: string; auth_token?: string };
  if (!r.ok) {
    throw new Error(j.detail || "Login failed");
  }
  if (j.auth_token) sessionStorage.setItem(AUTH_TOKEN_KEY, j.auth_token);
}

export async function logout(): Promise<void> {
  await apiFetch(`${API}/api/logout`, { method: "POST" });
  sessionStorage.removeItem(AUTH_TOKEN_KEY);
}