web: fix auth session races, ws token drift, and unread clear behavior
Some checks failed
CI / test (push) Failing after 2m20s
Some checks failed
CI / test (push) Failing after 2m20s
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import axios from "axios";
|
||||
import type { AxiosError, InternalAxiosRequestConfig } from "axios";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
|
||||
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "/api/v1";
|
||||
@@ -15,3 +16,37 @@ http.interceptors.request.use((config) => {
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
let refreshInFlight: Promise<void> | null = null;
|
||||
|
||||
function shouldSkipRefresh(config?: InternalAxiosRequestConfig): boolean {
|
||||
const url = config?.url ?? "";
|
||||
return url.includes("/auth/login") || url.includes("/auth/refresh");
|
||||
}
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error: AxiosError) => {
|
||||
const status = error.response?.status;
|
||||
const originalRequest = error.config as (InternalAxiosRequestConfig & { _retry?: boolean }) | undefined;
|
||||
if (!originalRequest || status !== 401 || originalRequest._retry || shouldSkipRefresh(originalRequest)) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
originalRequest._retry = true;
|
||||
const authStore = useAuthStore.getState();
|
||||
|
||||
try {
|
||||
if (!refreshInFlight) {
|
||||
refreshInFlight = authStore.refresh().finally(() => {
|
||||
refreshInFlight = null;
|
||||
});
|
||||
}
|
||||
await refreshInFlight;
|
||||
return http.request(originalRequest);
|
||||
} catch (refreshError) {
|
||||
useAuthStore.getState().logout();
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user