36 lines
903 B
JavaScript
36 lines
903 B
JavaScript
|
|
import { API_BASE_URL } from './apiConfig';
|
||
|
|
|
||
|
|
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 = (resource, options = {}) => {
|
||
|
|
if (!shouldAttachToken(resource)) {
|
||
|
|
return nativeFetch(resource, options);
|
||
|
|
}
|
||
|
|
|
||
|
|
const headers = new Headers(options.headers || {});
|
||
|
|
|
||
|
|
if (!headers.has('Authorization')) {
|
||
|
|
headers.set('Authorization', `Bearer ${getStoredToken()}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
return nativeFetch(resource, {
|
||
|
|
...options,
|
||
|
|
headers,
|
||
|
|
});
|
||
|
|
};
|
||
|
|
}
|