mirror of
https://github.com/lordmathis/lemma.git
synced 2025-11-05 15:44:21 +00:00
Refactor API call to include CSRF token handling for non-GET requests
This commit is contained in:
@@ -1,5 +1,22 @@
|
||||
import { refreshToken } from './auth';
|
||||
|
||||
/**
|
||||
* Gets the CSRF token from cookies
|
||||
* @returns {string} The CSRF token or an empty string if not found
|
||||
*/
|
||||
const getCsrfToken = (): string => {
|
||||
const cookies = document.cookie.split(';');
|
||||
let csrfToken = '';
|
||||
for (const cookie of cookies) {
|
||||
const [name, value] = cookie.trim().split('=');
|
||||
if (name === 'csrf_token' && value) {
|
||||
csrfToken = decodeURIComponent(value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return csrfToken;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes an API call with proper cookie handling and error handling
|
||||
*/
|
||||
@@ -9,14 +26,26 @@ export const apiCall = async (
|
||||
): Promise<Response> => {
|
||||
console.debug(`Making API call to: ${url}`);
|
||||
try {
|
||||
// Set up headers with CSRF token for non-GET requests
|
||||
const method = options.method || 'GET';
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
// Add CSRF token for non-GET methods
|
||||
if (method !== 'GET') {
|
||||
const csrfToken = getCsrfToken();
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
// Include credentials to send/receive cookies
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
headers,
|
||||
});
|
||||
console.debug(`Response status: ${response.status} for URL: ${url}`);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user