felicity-lims/webapp/axios/with-auth.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-02-06 03:36:45 +08:00
import axios from 'axios';
2023-04-10 09:29:10 +08:00
import { getAuthData, authLogout } from '../auth';
2022-12-28 05:29:14 +08:00
// import router from "../router";
2022-02-06 03:36:45 +08:00
2023-04-10 09:29:10 +08:00
import { REST_BASE_URL } from '../conf';
2022-02-06 03:36:45 +08:00
2022-03-07 04:39:34 +08:00
const getAuthHeaders = async () => {
2023-04-10 09:29:10 +08:00
const authData = getAuthData();
2022-04-04 02:54:31 +08:00
2023-04-10 09:29:10 +08:00
if (authData?.auth?.token) {
return {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
...(authData?.auth?.token && {
'x-felicity-user-id': 'felicity-user',
'x-felicity-role': 'felicity-administrator',
Authorization: `Bearer ${authData?.auth?.token}`,
}),
};
}
authLogout();
// router.push("/auth")
2022-03-06 02:06:07 +08:00
};
2022-02-06 03:36:45 +08:00
const axiosInstance = axios.create({
2023-04-10 09:29:10 +08:00
baseURL: REST_BASE_URL + '/api/v1/',
timeout: 1000,
headers: await getAuthHeaders(),
});
2022-02-06 03:36:45 +08:00
2022-12-28 05:29:14 +08:00
// NEW
axios.interceptors.response.use(undefined, function (error) {
2023-04-10 09:29:10 +08:00
if (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
authLogout();
// return router.push("/auth")
}
2022-12-28 05:29:14 +08:00
}
});
2023-04-10 09:29:10 +08:00
export default axiosInstance;