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

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-02-06 03:36:45 +08:00
import axios from 'axios';
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
2022-04-22 03:33:54 +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 () => {
2022-04-04 02:54:31 +08:00
const authData = getAuthData();
2022-04-04 02:54:31 +08:00
if (authData?.auth?.token) {
2022-02-06 03:36:45 +08:00
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 && {
2022-02-06 03:36:45 +08:00
'x-felicity-user-id': "felicity-user",
'x-felicity-role': "felicity-administrator",
'Authorization': `Bearer ${authData?.auth?.token}`
2022-02-06 03:36:45 +08:00
}),
}
}
authLogout();
2022-12-28 05:29:14 +08:00
// router.push("/auth")
2022-03-06 02:06:07 +08:00
};
2022-02-06 03:36:45 +08:00
const axiosInstance = axios.create({
baseURL: REST_BASE_URL + "/api/v1/",
timeout: 1000,
2022-03-07 04:39:34 +08:00
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) {
if (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
authLogout();
// return router.push("/auth")
}
}
});
2022-02-06 03:36:45 +08:00
export default axiosInstance