mirror of
https://github.com/lordmathis/lemma.git
synced 2025-11-05 23:44:22 +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';
|
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
|
* Makes an API call with proper cookie handling and error handling
|
||||||
*/
|
*/
|
||||||
@@ -9,14 +26,26 @@ export const apiCall = async (
|
|||||||
): Promise<Response> => {
|
): Promise<Response> => {
|
||||||
console.debug(`Making API call to: ${url}`);
|
console.debug(`Making API call to: ${url}`);
|
||||||
try {
|
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, {
|
const response = await fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
// Include credentials to send/receive cookies
|
// Include credentials to send/receive cookies
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
headers: {
|
headers,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...options.headers,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
console.debug(`Response status: ${response.status} for URL: ${url}`);
|
console.debug(`Response status: ${response.status} for URL: ${url}`);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user