import { API_BASE_URL } from './apiConfig'; import { clearSession } from '../../modules/auth/services/sessionService'; function getStoredToken() { return window.sessionStorage.getItem('authToken'); } function shouldAttachToken(resource) { const url = typeof resource === 'string' ? resource : resource?.url; return Boolean(url && url.startsWith(API_BASE_URL) && getStoredToken()); } export function installAuthFetchInterceptor() { window.localStorage.removeItem('authToken'); window.localStorage.removeItem('authUser'); const nativeFetch = window.fetch.bind(window); window.fetch = async (resource, options = {}) => { if (!shouldAttachToken(resource)) { return nativeFetch(resource, options); } const headers = new Headers(options.headers || {}); if (!headers.has('Authorization')) { headers.set('Authorization', `Bearer ${getStoredToken()}`); } const response = await nativeFetch(resource, { ...options, headers, }); if (response.status === 401) { clearSession(); if (window.location.pathname !== '/login') { window.location.assign('/login'); } } return response; }; }