Spaces:
Sleeping
Sleeping
| import axios from "axios" | |
| const api = axios.create({ | |
| baseURL: window.location.hostname === "localhost" ? "http://localhost:8000" : "", | |
| }) | |
| api.interceptors.request.use((config) => { | |
| const token = sessionStorage.getItem("access_token") | |
| if (token) { | |
| config.headers.Authorization = `Bearer ${token}` | |
| } | |
| return config | |
| }, (error) => { | |
| return Promise.reject(error) | |
| }) | |
| api.interceptors.response.use( | |
| (res) => res, | |
| async (error) => { | |
| const originalRequest = error.config | |
| if (error.response?.status === 401 && !originalRequest._retry) { | |
| originalRequest._retry = true | |
| const refresh = sessionStorage.getItem("refresh_token") | |
| if (!refresh) { | |
| sessionStorage.clear() | |
| window.location.href = "/login" | |
| return Promise.reject(error) | |
| } | |
| try { | |
| const baseURL = window.location.hostname === "localhost" ? "http://localhost:8000" : ""; | |
| const { data } = await axios.post(`${baseURL}/auth/refresh`, { | |
| refresh_token: refresh, | |
| }) | |
| sessionStorage.setItem("access_token", data.access_token) | |
| sessionStorage.setItem("refresh_token", data.refresh_token) | |
| originalRequest.headers.Authorization = `Bearer ${data.access_token}` | |
| return api(originalRequest) | |
| } catch (refreshError) { | |
| sessionStorage.clear() | |
| window.location.href = "/login" | |
| return Promise.reject(refreshError) | |
| } | |
| } | |
| return Promise.reject(error) | |
| } | |
| ) | |
| export default api | |