fix(frontend): logout state not shown after JWT expires (#40)
Reviewed-on: #40
This commit was merged in pull request #40.
This commit is contained in:
@@ -6,9 +6,43 @@ class AuthError extends Error {
|
||||
constructor() { super("Not authenticated"); this.name = "AuthError"; }
|
||||
}
|
||||
|
||||
const isThumbnailAvailable = async (thumbnailUrl: string): Promise<boolean> => {
|
||||
const response = await fetch(thumbnailUrl, { credentials: 'include' });
|
||||
return response.ok;
|
||||
};
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
|
||||
export { API_URL, AuthError, isThumbnailAvailable };
|
||||
export function registerUnauthorizedHandler(handler: () => void) {
|
||||
onUnauthorized = handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a request against the API, sending session cookies and funnelling
|
||||
* expired/missing sessions through the registered unauthorized handler so the
|
||||
* UI can drop back to a logged out state. Returns the raw response so callers
|
||||
* that need something other than JSON (blobs, streams) can read it themselves.
|
||||
*/
|
||||
async function apiFetchRaw(url: string, options: RequestInit = {}): Promise<Response> {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.status == 401 || response.status == 403) {
|
||||
onUnauthorized?.();
|
||||
throw new AuthError();
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
let message = text;
|
||||
try { message = JSON.parse(text).message ?? text; } catch { /* not JSON, use raw text */ }
|
||||
throw new Error(message || `Request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async function apiFetch<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
const response = await apiFetchRaw(url, options);
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : (undefined as T);
|
||||
}
|
||||
|
||||
export { API_URL, AuthError, apiFetch, apiFetchRaw };
|
||||
|
||||
Reference in New Issue
Block a user