Adds supports for RefreshTokens
This commit is contained in:
@@ -4,42 +4,52 @@ import {useAuthStore} from "@/stores/authStore.js"
|
||||
export function useClient() {
|
||||
if (!import.meta.env.VITE_API_URL) throw new Error("VITE_API_URL is not provided")
|
||||
|
||||
const api = axios.create({
|
||||
const authStore = useAuthStore()
|
||||
const client = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const requestInterceptor = (config) => {
|
||||
// Request interceptor
|
||||
client.interceptors.request.use(async (config) => {
|
||||
// Proactively check and refresh token if needed
|
||||
if (authStore.isAuthenticated) {
|
||||
config.headers["Authorization"] = `Bearer ${authStore.accessToken}`
|
||||
try {
|
||||
console.log('within api call')
|
||||
await authStore.ensureValidToken();
|
||||
} catch (error) {
|
||||
console.error('Failed to ensure valid token:', error);
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
api.interceptors.request.use(requestInterceptor);
|
||||
if (authStore.isAuthenticated) {
|
||||
config.headers.Authorization = `Bearer ${authStore.accessToken}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// Add response interceptor for token refresh
|
||||
api.interceptors.response.use(
|
||||
// Response interceptor
|
||||
client.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
// If error is 401 and we haven't tried to refresh the token yet
|
||||
// If the error is 401 and we haven't tried to refresh the token yet
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
console.log('Received 401 error, attempting token refresh...');
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
// Attempt to refresh the token
|
||||
await authStore.refresh();
|
||||
|
||||
console.log('Token refresh successful, retrying original request...');
|
||||
// Retry the original request with the new token
|
||||
originalRequest.headers["Authorization"] = `Bearer ${authStore.accessToken}`;
|
||||
return api(originalRequest);
|
||||
return client(originalRequest);
|
||||
} catch (refreshError) {
|
||||
// If refresh fails, logout the user
|
||||
console.error('Token refresh failed, logging out user:', refreshError);
|
||||
await authStore.logout();
|
||||
return Promise.reject(refreshError);
|
||||
throw refreshError;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +57,6 @@ export function useClient() {
|
||||
}
|
||||
);
|
||||
|
||||
return api;
|
||||
return client;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user