36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
// Cookie-based auth fetch used across the app.
|
|
// - Does NOT read from localStorage.
|
|
// - Sends cookies automatically (credentials: 'include').
|
|
// - Keeps the same behavior: return Response, or null on 401/403.
|
|
|
|
let onSessionExpiredCallback = null;
|
|
|
|
export const setSessionExpiredCallback = (callback) => {
|
|
onSessionExpiredCallback = callback;
|
|
};
|
|
|
|
const authFetch = async (url, options = {}) => {
|
|
const method = (options.method || 'GET').toUpperCase();
|
|
const hasCTHeader = options.headers && Object.prototype.hasOwnProperty.call(options.headers, 'Content-Type');
|
|
const shouldIncludeContentType = ['POST','PUT','PATCH'].includes(method) && !hasCTHeader;
|
|
|
|
const res = await fetch(url, {
|
|
credentials: 'include', // <-- send httpOnly session cookie
|
|
...options,
|
|
headers: {
|
|
...(shouldIncludeContentType ? { 'Content-Type': 'application/json' } : {}),
|
|
Accept: 'application/json',
|
|
...(options.headers || {}),
|
|
},
|
|
});
|
|
|
|
if (res.status === 401 || res.status === 403) {
|
|
onSessionExpiredCallback?.();
|
|
return null;
|
|
}
|
|
|
|
return res;
|
|
};
|
|
|
|
export default authFetch;
|