| const API = ""; |
|
|
| |
| 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; |
|
|
| |
| 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); |
| } |
|
|