| 1 | import type { AxiosRequestHeaders } from "axios" |
| 2 | import axios from "axios" |
| 3 | import { useAuthStore } from "@/stores/auth" |
| 4 | import { isDebounceTimeOver, isJwtExpiring } from "@/utils/auth" |
| 5 | // import { useGlobalActions } from "@/composables/useGlobalActions" |
| 6 | |
| 7 | const HttpClient = axios.create({ |
| 8 | baseURL: "/api" |
| 9 | }) |
| 10 | |
| 11 | let __TOKEN_REFRESHING = false |
| 12 | let __TOKEN_LAST_CHECK: Date | null = null |
| 13 | |
| 14 | HttpClient.interceptors.request.use( |
| 15 | config => { |
| 16 | const store = useAuthStore() |
| 17 | |
| 18 | if (!config.headers) config.headers = {} as AxiosRequestHeaders |
| 19 | if (store.userToken) { |
| 20 | config.headers.Authorization = `Bearer ${store.userToken}` |
| 21 | } |
| 22 | |
| 23 | if ( |
| 24 | store.userToken && |
| 25 | isJwtExpiring(store.userToken, 60 * 60) && |
| 26 | !__TOKEN_REFRESHING && |
| 27 | isDebounceTimeOver(__TOKEN_LAST_CHECK) |
| 28 | ) { |
| 29 | __TOKEN_REFRESHING = true |
| 30 | __TOKEN_LAST_CHECK = new Date() |
| 31 | |
| 32 | store.refreshToken().then(() => { |
| 33 | __TOKEN_REFRESHING = false |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | return config |
| 38 | }, |
| 39 | error => Promise.reject(error) |
| 40 | ) |
| 41 | |
| 42 | HttpClient.interceptors.response.use( |
| 43 | response => response, |
| 44 | error => { |
| 45 | if (error.response && error.response.status === 401) { |
| 46 | if (!window.location.pathname.includes("login")) { |
| 47 | window.location.href = "/logout" |
| 48 | } |
| 49 | /* |
| 50 | useGlobalActions().message("You are not authorized to access the resource", { type: "error" }) |
| 51 | */ |
| 52 | } |
| 53 | |
| 54 | return Promise.reject(error) |
| 55 | } |
| 56 | ) |
| 57 | |
| 58 | export { HttpClient } |