This commit is contained in:
Tomas Dvorak
2025-11-02 01:04:02 +01:00
parent ac886502e0
commit b9cea0cd77
153 changed files with 43713 additions and 1700 deletions
+37 -2
View File
@@ -35,14 +35,49 @@ export const api: AxiosInstance = axios.create({
timeout: 20000, // 20 seconds to better tolerate slower endpoints
});
// Simple in-memory CSRF token cache
let csrfTokenCache: { token: string; fetchedAt: number } | null = null;
async function getCsrfToken(): Promise<string | null> {
try {
// Refresh token every 45 minutes
const now = Date.now();
if (csrfTokenCache && now - csrfTokenCache.fetchedAt < 45 * 60 * 1000) {
return csrfTokenCache.token;
}
const res = await fetch(`${API_URL.replace(/\/$/, '')}/csrf-token`, {
credentials: 'include',
headers: { 'Accept': 'application/json' },
});
if (!res.ok) return null;
const data = await res.json();
const token = data?.csrf_token || null;
if (token) {
csrfTokenCache = { token, fetchedAt: now };
}
return token;
} catch {
return null;
}
}
// Request interceptor - attach bearer token when available
api.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
async (config: InternalAxiosRequestConfig) => {
const token = getToken();
config.headers = config.headers || {};
if (token) {
config.headers = config.headers || {};
(config.headers as any).Authorization = `Bearer ${token}`;
}
// For cookie-based flows (no Bearer header), attach X-CSRF-Token on mutating methods
const method = (config.method || 'get').toLowerCase();
const isMutating = method === 'post' || method === 'put' || method === 'patch' || method === 'delete';
const hasAuth = !!(config.headers as any).Authorization;
if (isMutating && !hasAuth) {
const csrf = await getCsrfToken();
if (csrf) {
(config.headers as any)['X-CSRF-Token'] = csrf;
}
}
return config;
},
(error) => {