Panel admina: naglowek X-Client przy auth (wlasne ciastko refresh), upload zdjec i pobieranie dokumentow przez klient API ( FormData/blob, rotacja 401)
This commit is contained in:
@@ -23,11 +23,16 @@ export function getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
// Panel admina i SPA dzielą domenę (różne porty), a ciastka portów nie
|
||||
// rozróżniają — nagłówek mówi API, by sięgało po ciastko `fitos_admin_refresh`.
|
||||
const CLIENT_HEADER = { 'X-Client': 'admin' } as const;
|
||||
|
||||
async function tryRefresh(): Promise<boolean> {
|
||||
if (!refreshing) {
|
||||
refreshing = fetch(`${API_BASE}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { ...CLIENT_HEADER },
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) return false;
|
||||
@@ -43,21 +48,39 @@ async function tryRefresh(): Promise<boolean> {
|
||||
return refreshing;
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, opts: { method?: string; body?: unknown } = {}): Promise<T> {
|
||||
async function fetchWithAuth(
|
||||
path: string,
|
||||
opts: { method?: string; body?: unknown } = {},
|
||||
): Promise<Response> {
|
||||
const isFormData = typeof FormData !== 'undefined' && opts.body instanceof FormData;
|
||||
const doFetch = () =>
|
||||
fetch(`${API_BASE}${path}`, {
|
||||
method: opts.method || 'GET',
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
// FormData: przeglądarka sama stawia multipart boundary
|
||||
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
||||
...CLIENT_HEADER,
|
||||
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||||
},
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
body:
|
||||
opts.body === undefined
|
||||
? undefined
|
||||
: isFormData
|
||||
? (opts.body as FormData)
|
||||
: JSON.stringify(opts.body),
|
||||
});
|
||||
|
||||
let res = await doFetch();
|
||||
|
||||
if (res.status === 401 && path !== '/auth/refresh' && path !== '/auth/login' && path !== '/auth/register') {
|
||||
// Wylogowanie musi przejść nawet bez ważnego tokenu — odświeżanie/próba
|
||||
// ponowna przy 401 zapętlają się (handler fitos:logout znowu woła /auth/logout).
|
||||
const isAuthEntry =
|
||||
path === '/auth/refresh' ||
|
||||
path === '/auth/login' ||
|
||||
path === '/auth/register' ||
|
||||
path === '/auth/logout';
|
||||
if (res.status === 401 && !isAuthEntry) {
|
||||
const ok = await tryRefresh();
|
||||
if (ok) res = await doFetch();
|
||||
else {
|
||||
@@ -65,7 +88,10 @@ export async function api<T>(path: string, opts: { method?: string; body?: unkno
|
||||
window.dispatchEvent(new Event('fitos:logout'));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async function toApiError(res: Response): Promise<ApiError> {
|
||||
const text = await res.text();
|
||||
let json: unknown = null;
|
||||
if (text) {
|
||||
@@ -75,9 +101,34 @@ export async function api<T>(path: string, opts: { method?: string; body?: unkno
|
||||
// ciało nie-JSON (np. rate limiter, proxy) — traktujemy jako nieprzezroczysty błąd
|
||||
}
|
||||
}
|
||||
if (!res.ok) {
|
||||
const body = (json ?? (text ? { error: { code: `HTTP_${res.status}`, message: text } } : null)) as ApiErrorBody | null;
|
||||
throw new ApiError(res.status, body);
|
||||
const body = (json ??
|
||||
(text
|
||||
? { error: { code: `HTTP_${res.status}`, message: text } }
|
||||
: null)) as ApiErrorBody | null;
|
||||
return new ApiError(res.status, body);
|
||||
}
|
||||
|
||||
export async function api<T>(
|
||||
path: string,
|
||||
opts: { method?: string; body?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const res = await fetchWithAuth(path, opts);
|
||||
if (!res.ok) throw await toApiError(res);
|
||||
const text = await res.text();
|
||||
let json: unknown = null;
|
||||
if (text) {
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
// pusty/nie-JSON 2xx (np. 204) — zwracamy null
|
||||
}
|
||||
}
|
||||
return json as T;
|
||||
}
|
||||
|
||||
/** Pobranie binarnych zasobów (zdjęcia, dokumenty weryfikacji) z bearerem i rotacją 401. */
|
||||
export async function apiBlob(path: string): Promise<Blob> {
|
||||
const res = await fetchWithAuth(path);
|
||||
if (!res.ok) throw await toApiError(res);
|
||||
return res.blob();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user