mirror of
https://github.com/Dvorinka/MyClubServer.git
synced 2026-06-04 02:32:57 +00:00
dev day #79
This commit is contained in:
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user