44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
/**
|
|
* Authenticated fetch helpers for rApp frontends.
|
|
*
|
|
* Wraps the native `fetch()` to inject the EncryptID bearer token,
|
|
* and provides a `requireAuth()` gate that shows the auth modal when needed.
|
|
*/
|
|
|
|
import { getAccessToken, isAuthenticated } from "./components/rstack-identity";
|
|
|
|
/**
|
|
* Fetch wrapper that injects `Authorization: Bearer <token>`.
|
|
* Skips Content-Type for FormData (browser sets multipart boundary).
|
|
*/
|
|
export async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
const token = getAccessToken();
|
|
const headers = new Headers(init?.headers);
|
|
|
|
if (token) {
|
|
headers.set("Authorization", `Bearer ${token}`);
|
|
}
|
|
|
|
// Don't override Content-Type for FormData — browser sets multipart boundary
|
|
if (init?.body instanceof FormData) {
|
|
headers.delete("Content-Type");
|
|
}
|
|
|
|
return fetch(input, { ...init, headers });
|
|
}
|
|
|
|
/**
|
|
* Check authentication and show the auth modal if not authenticated.
|
|
* Returns `true` if authenticated, `false` if not (modal shown).
|
|
*/
|
|
export function requireAuth(actionLabel?: string): boolean {
|
|
if (isAuthenticated()) return true;
|
|
|
|
const identityEl = document.querySelector("rstack-identity") as any;
|
|
if (identityEl?.showAuthModal) {
|
|
identityEl.showAuthModal();
|
|
}
|
|
|
|
return false;
|
|
}
|