2026-05-29 12:27:37 -03:00
|
|
|
import { API_BASE_URL } from './apiConfig';
|
2026-06-01 17:13:46 -03:00
|
|
|
import { clearSession, getAuthToken } from '../../modules/auth/services/sessionService';
|
2026-05-29 12:27:37 -03:00
|
|
|
|
|
|
|
|
function shouldAttachToken(resource) {
|
|
|
|
|
const url = typeof resource === 'string' ? resource : resource?.url;
|
|
|
|
|
|
2026-06-01 17:13:46 -03:00
|
|
|
return Boolean(url && url.startsWith(API_BASE_URL) && getAuthToken());
|
2026-05-29 12:27:37 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function installAuthFetchInterceptor() {
|
|
|
|
|
window.localStorage.removeItem('authToken');
|
|
|
|
|
window.localStorage.removeItem('authUser');
|
|
|
|
|
|
|
|
|
|
const nativeFetch = window.fetch.bind(window);
|
|
|
|
|
|
2026-06-01 16:56:09 -03:00
|
|
|
window.fetch = async (resource, options = {}) => {
|
2026-05-29 12:27:37 -03:00
|
|
|
if (!shouldAttachToken(resource)) {
|
|
|
|
|
return nativeFetch(resource, options);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const headers = new Headers(options.headers || {});
|
|
|
|
|
|
|
|
|
|
if (!headers.has('Authorization')) {
|
2026-06-01 17:13:46 -03:00
|
|
|
headers.set('Authorization', `Bearer ${getAuthToken()}`);
|
2026-05-29 12:27:37 -03:00
|
|
|
}
|
|
|
|
|
|
2026-06-01 16:56:09 -03:00
|
|
|
const response = await nativeFetch(resource, {
|
2026-05-29 12:27:37 -03:00
|
|
|
...options,
|
|
|
|
|
headers,
|
|
|
|
|
});
|
2026-06-01 16:56:09 -03:00
|
|
|
|
|
|
|
|
if (response.status === 401) {
|
|
|
|
|
clearSession();
|
|
|
|
|
|
|
|
|
|
if (window.location.pathname !== '/login') {
|
|
|
|
|
window.location.assign('/login');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return response;
|
2026-05-29 12:27:37 -03:00
|
|
|
};
|
|
|
|
|
}
|