86 lines
2.1 KiB
TypeScript
86 lines
2.1 KiB
TypeScript
import { ENV_CONSTANT } from '@/constants/secrect.constant';
|
|
import { useAppStore } from '@/store/app.store';
|
|
import { useAuthStore } from '@/store/auth.store';
|
|
import axios from 'axios';
|
|
|
|
const BASE_URL = ENV_CONSTANT.BASE_API_URL;
|
|
|
|
const axiosClient = axios.create({
|
|
baseURL: BASE_URL,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'ngrok-skip-browser-warning': 'true',
|
|
},
|
|
});
|
|
|
|
axiosClient.interceptors.request.use(
|
|
(config) => {
|
|
const token = useAuthStore.getState().accessToken;
|
|
|
|
if (token && config.headers) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
axiosClient.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
const originalRequest = error?.config;
|
|
const status = error?.response?.status;
|
|
const requestUrl = originalRequest?.url ?? '';
|
|
const isAuthRoute =
|
|
requestUrl.includes('api/auth/login') || requestUrl.includes('api/auth/refresh');
|
|
|
|
if (status === 401 && originalRequest && !originalRequest._retry && !isAuthRoute) {
|
|
originalRequest._retry = true;
|
|
|
|
try {
|
|
const response = await axiosAuth.post(
|
|
'api/auth/refresh',
|
|
{},
|
|
{
|
|
withCredentials: true,
|
|
},
|
|
);
|
|
const accessToken = response.data?.access_token;
|
|
|
|
if (!accessToken) {
|
|
throw new Error('Refresh failed: no access token');
|
|
}
|
|
|
|
useAuthStore.getState().setAccessToken(accessToken);
|
|
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
|
|
|
return axiosClient(originalRequest);
|
|
} catch (refreshError) {
|
|
useAuthStore.getState().logout();
|
|
useAppStore.getState().clear();
|
|
|
|
if (typeof window !== 'undefined') {
|
|
window.location.href = '/login';
|
|
}
|
|
|
|
return Promise.reject(refreshError);
|
|
}
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
export const axiosAuth = axios.create({
|
|
baseURL: BASE_URL,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'ngrok-skip-browser-warning': 'true',
|
|
},
|
|
});
|
|
|
|
export default axiosClient;
|