felicity-lims/frontend/vite/src/axios/with-auth.ts

32 lines
833 B
TypeScript
Raw Normal View History

2022-02-06 03:36:45 +08:00
import axios from 'axios';
2022-04-22 03:33:54 +08:00
import { useAuthStore } from "../stores"
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 authStore = useAuthStore();
if (authStore?.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',
2022-04-04 02:54:31 +08:00
...(authStore?.auth?.token && {
2022-02-06 03:36:45 +08:00
'x-felicity-user-id': "felicity-user",
'x-felicity-role': "felicity-administrator",
2022-04-04 02:54:31 +08:00
'Authorization': `Bearer ${authStore?.auth?.token}`
2022-02-06 03:36:45 +08:00
}),
}
}
2022-04-04 02:54:31 +08:00
authStore.logout();
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
})
export default axiosInstance