dev1/src/utils/authFetch.js
Josh 5838f782e7
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
removed files from tracking, dependencies, fixed encryption
2025-08-19 12:24:54 +00:00

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;