39 lines
1012 B
TypeScript
39 lines
1012 B
TypeScript
import axios from 'axios';
|
|
|
|
const PORTAL_TOKEN_KEY = 'mento_portal_token';
|
|
|
|
export function getPortalToken() {
|
|
return localStorage.getItem(PORTAL_TOKEN_KEY);
|
|
}
|
|
|
|
export function setPortalToken(token: string | null) {
|
|
if (token) localStorage.setItem(PORTAL_TOKEN_KEY, token);
|
|
else localStorage.removeItem(PORTAL_TOKEN_KEY);
|
|
}
|
|
|
|
export const portalApi = axios.create({
|
|
baseURL: '/api',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
portalApi.interceptors.request.use((config) => {
|
|
const token = getPortalToken();
|
|
if (token) config.headers.Authorization = `Bearer ${token}`;
|
|
return config;
|
|
});
|
|
|
|
portalApi.interceptors.response.use(
|
|
(r) => r,
|
|
(error) => {
|
|
if (axios.isAxiosError(error) && error.response?.status === 401) {
|
|
setPortalToken(null);
|
|
const path = window.location.pathname;
|
|
const m = path.match(/^\/p\/([^/]+)/);
|
|
if (m && !path.endsWith('/login')) {
|
|
window.location.assign(`/p/${m[1]}`);
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
},
|
|
);
|