f3c80de219
- client.ts: handle 401 responses by attempting token refresh, then logout and redirect to /login on failure - Keys.tsx: add actionError state, surface API errors from handleRename and handleFreeze with visible error banner Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
83 lines
2.3 KiB
TypeScript
83 lines
2.3 KiB
TypeScript
import { useAuthStore } from "../store/auth";
|
|
|
|
const BASE = "/api";
|
|
|
|
async function request(
|
|
url: string,
|
|
options: RequestInit = {},
|
|
withAuth = true
|
|
): Promise<any> {
|
|
const headers: Record<string, string> = {
|
|
"Content-Type": "application/json",
|
|
...(options.headers as Record<string, string>),
|
|
};
|
|
|
|
if (withAuth) {
|
|
const token = useAuthStore.getState().accessToken;
|
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
}
|
|
|
|
const res = await fetch(`${BASE}${url}`, { ...options, headers });
|
|
|
|
if (res.status === 401 && withAuth) {
|
|
const refreshToken = useAuthStore.getState().refreshToken;
|
|
if (refreshToken) {
|
|
const refreshRes = await fetch(`${BASE}/web/refresh`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ refresh_token: refreshToken }),
|
|
});
|
|
if (refreshRes.ok) {
|
|
const data = await refreshRes.json();
|
|
if (data.ok) {
|
|
useAuthStore.getState().setAuth(
|
|
data.access_token,
|
|
data.refresh_token,
|
|
useAuthStore.getState().user!
|
|
);
|
|
headers["Authorization"] = `Bearer ${data.access_token}`;
|
|
const retryRes = await fetch(`${BASE}${url}`, { ...options, headers });
|
|
return retryRes.json();
|
|
}
|
|
}
|
|
}
|
|
useAuthStore.getState().logout();
|
|
window.location.href = "/login";
|
|
return { ok: false, error: "Session expired" };
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
export const api = {
|
|
register: (email: string, password: string, name?: string) =>
|
|
request("/web/register", {
|
|
method: "POST",
|
|
body: JSON.stringify({ email, password, name }),
|
|
}, false),
|
|
|
|
login: (email: string, password: string) =>
|
|
request("/web/login", {
|
|
method: "POST",
|
|
body: JSON.stringify({ email, password }),
|
|
}, false),
|
|
|
|
tgAuth: (data: Record<string, any>) =>
|
|
request("/web/tg_auth", {
|
|
method: "POST",
|
|
body: JSON.stringify(data),
|
|
}, false),
|
|
|
|
refresh: (refresh_token: string) =>
|
|
request("/web/refresh", {
|
|
method: "POST",
|
|
body: JSON.stringify({ refresh_token }),
|
|
}, false),
|
|
|
|
action: (action: string, payload: Record<string, any> = {}) =>
|
|
request("/web/action", {
|
|
method: "POST",
|
|
body: JSON.stringify({ action, payload }),
|
|
}),
|
|
};
|