fix: fixes to session storage
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m27s
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m27s
This commit is contained in:
@@ -3,23 +3,57 @@ import { useAuthStore } from "../stores/authStore";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || "http://localhost:8080",
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
const authStore = useAuthStore();
|
||||
if (authStore.accessToken) {
|
||||
config.headers.Authorization = `Bearer ${authStore.accessToken}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
let isRefreshing = false;
|
||||
let refreshSubscribers = [];
|
||||
|
||||
function onRefreshed() {
|
||||
refreshSubscribers.forEach((cb) => cb());
|
||||
refreshSubscribers = [];
|
||||
}
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
const authStore = useAuthStore();
|
||||
authStore.logout();
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
// Avoid retrying the refresh request itself
|
||||
if (originalRequest.url?.includes("/auth/refresh") || originalRequest.url?.includes("/auth/login")) {
|
||||
const authStore = useAuthStore();
|
||||
authStore.clearSession();
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
if (isRefreshing) {
|
||||
// Queue the request until the ongoing refresh completes
|
||||
return new Promise((resolve, reject) => {
|
||||
refreshSubscribers.push(() => {
|
||||
originalRequest._retry = true;
|
||||
apiClient(originalRequest).then(resolve).catch(reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
originalRequest._retry = true;
|
||||
isRefreshing = true;
|
||||
|
||||
try {
|
||||
await apiClient.post("/api/v1/auth/refresh");
|
||||
onRefreshed();
|
||||
return apiClient(originalRequest);
|
||||
} catch {
|
||||
refreshSubscribers = [];
|
||||
const authStore = useAuthStore();
|
||||
authStore.clearSession();
|
||||
return Promise.reject(error);
|
||||
} finally {
|
||||
isRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user