fix(auth): handles expired tokens correctly

This commit is contained in:
2025-05-09 01:53:44 -04:00
parent b8e94f6409
commit 23ab1cc85d
3 changed files with 305 additions and 235 deletions

View File

@@ -1,69 +1,102 @@
import axios from "axios"
import {useAuthStore} from "@/stores/authStore.js"
import axios from 'axios';
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")
if (!import.meta.env.VITE_API_URL) {
throw new Error('VITE_API_URL is not provided');
}
const authStore = useAuthStore()
const client = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
'Content-Type': 'application/json',
},
'Content-Type': 'application/json'
}
});
const authStore = useAuthStore();
// Request interceptor
client.interceptors.request.use(async (config) => {
// Proactively check and refresh token if needed
if (authStore.isAuthenticated) {
console.log(`Request interceptor triggered for: ${config.method?.toUpperCase()} ${config.url}`);
// Check if this is the refresh token endpoint
const isRefreshEndpoint = config.url?.includes('api/users/refresh');
// Check if we need to refresh the token
if (authStore.isAuthenticated && !isRefreshEndpoint) {
try {
await authStore.ensureValidToken();
console.log(`User is authenticated, checking token for: ${config.method?.toUpperCase()} ${config.url}`);
// If token is expiring soon, start a refresh and WAIT for it to complete
if (authStore.isTokenExpiringSoon(authStore.accessToken)) {
console.log(`Token is expiring soon, waiting for refresh to complete before continuing request: ${config.method?.toUpperCase()} ${config.url}`);
await authStore.refresh();
console.log(`Token refresh completed, proceeding with request: ${config.method?.toUpperCase()} ${config.url}`);
}
} catch (error) {
console.error('Failed to ensure valid token:', error);
console.error(`Failed to refresh token for: ${config.method?.toUpperCase()} ${config.url}`, error);
throw error; // This will cancel the request
}
}
// Add authorization header if authenticated
if (authStore.isAuthenticated) {
if (authStore.isAuthenticated && !isRefreshEndpoint) {
console.log(`Setting Authorization header for: ${config.method?.toUpperCase()} ${config.url}`);
config.headers.Authorization = `Bearer ${authStore.accessToken}`;
} else if (isRefreshEndpoint) {
console.log(`Skipping Authorization header for refresh endpoint: ${config.method?.toUpperCase()} ${config.url}`);
}
// Don't override Content-Type for FormData requests
if (config.data instanceof FormData) {
// Let the browser set the correct Content-Type with boundary
console.log(`Data is FormData, removing explicit Content-Type header for: ${config.method?.toUpperCase()} ${config.url}`);
delete config.headers['Content-Type'];
}
return config;
});
// Response interceptor
client.interceptors.response.use(
(response) => response,
(response) => {
console.log(`Response received successfully for: ${response.config.method?.toUpperCase()} ${response.config.url}`);
return response;
},
async (error) => {
const originalRequest = error.config;
console.error(`Response interceptor caught an error for: ${originalRequest.method?.toUpperCase()} ${originalRequest.url}`, error);
// 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...');
// Prevent retry loops by checking if this is already a retry or a refresh request
if (error.response?.status === 401 && !originalRequest._retry && !originalRequest.url.includes('api/users/refresh')) {
console.log(`Received 401 error for: ${originalRequest.method?.toUpperCase()} ${originalRequest.url}, attempting token refresh...`);
originalRequest._retry = true;
try {
await authStore.refresh();
console.log('Token refresh successful, retrying original request...');
// Retry the original request with the new token
// Use a timeout to prevent hanging indefinitely
const refreshTimeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Token refresh timeout')), 10000); // 10s timeout
});
// Race the refresh against the timeout
await Promise.race([authStore.refresh(), refreshTimeout]);
console.log(`Token refresh successful, retrying original request: ${originalRequest.method?.toUpperCase()} ${originalRequest.url}`);
return client(originalRequest);
} catch (refreshError) {
console.error('Token refresh failed, logging out user:', refreshError);
await authStore.logout('/login');
console.error(`Token refresh failed for: ${originalRequest.method?.toUpperCase()} ${originalRequest.url}, logging out user:`, refreshError);
// Let the authStore handle the navigation with returnUrl
throw refreshError;
}
}
// If it's a refresh request that failed, or a retry that still failed, give up
if (originalRequest.url.includes('api/users/refresh') || originalRequest._retry) {
console.log(`Request permanently failed: ${originalRequest.method?.toUpperCase()} ${originalRequest.url}`);
// Don't do anything here, let the refresh error handling work
}
return Promise.reject(error);
}
);
return client;
}
}