learning_ai_common_plat/dashboards/admin-web/src/lib/proxy-fetch.ts
saravanakumardb1 ce0074d6ee fix(admin-web): proxy routes + pages use cookie-based auth
- Add getCurrentUserFromRequest() to auth-server.ts (checks cookies first, then Authorization header)
- Update all 34 proxy routes: getCurrentUser(req.headers.get('authorization')) → getCurrentUserFromRequest(req)
- Add createProxyFetch() shared helper in lib/proxy-fetch.ts (injects auth + product-id headers)
- Update 15 admin pages: replace inline fetch helpers with createProxyFetch
- Root cause: newer pages used bare fetch() without Authorization headers, causing 401s on all proxy routes
2026-03-21 20:31:30 -07:00

38 lines
1.2 KiB
TypeScript

/**
* Shared fetch helper for admin-web pages that call proxy API routes.
* Automatically injects Authorization + x-product-id headers from localStorage.
*/
function getAuthHeaders(): Record<string, string> {
if (typeof window === 'undefined') return {};
const headers: Record<string, string> = {};
const token = localStorage.getItem('admin_access_token');
if (token) headers['Authorization'] = `Bearer ${token}`;
const productId = localStorage.getItem('admin_selected_product');
if (productId) headers['x-product-id'] = productId;
return headers;
}
/**
* Creates a scoped fetch helper for a given proxy base path.
*
* Usage:
* const apiFetch = createProxyFetch('/api/jobs');
* const data = await apiFetch('list'); // GET /api/jobs/list
* await apiFetch('123', { method: 'PUT', body: ... });
*/
export function createProxyFetch(basePath: string) {
return async function proxyFetch(path: string, opts?: RequestInit) {
const url = !path || path.startsWith('?') ? `${basePath}${path}` : `${basePath}/${path}`;
const res = await fetch(url, {
...opts,
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
...opts?.headers,
},
});
return res.json();
};
}