tududi/frontend/utils/projectsService.ts
Chris 6c9902b584
fix: add CSRF token support to frontend requests (#1025)
This commit implements CSRF token support for all session-based API
requests to fix the "CSRF token missing" and "CSRF token mismatch" errors
introduced after CSRF protection was added in commit 62c4cc84.

Changes:
- Created csrfService.ts utility for fetching and caching CSRF tokens
- Added getPostHeadersWithCsrf() helper to authUtils for async token injection
- Updated all service files (*Service.ts) to include CSRF tokens in POST/PUT/PATCH/DELETE requests
- Updated components with inline fetch calls to use getCsrfToken()
- Fixed CSRF middleware to use single lusca instance instead of creating new instances per request
- Improved generateToken() to use req.csrfToken() when available
- Added CalDAV path exemption to CSRF protection

Technical details:
- CSRF tokens are fetched from /api/csrf-token endpoint
- Tokens are cached and reused across requests to avoid unnecessary fetches
- Tokens are included in x-csrf-token header for state-changing requests
- Public endpoints (login, register) remain exempt from CSRF protection
- Bearer token authentication remains exempt from CSRF protection

Files modified:
- Backend: app.js, middleware/csrf.js
- Frontend: 13 service files, 8 component files
- New file: frontend/utils/csrfService.ts

This ensures all session-based requests properly include CSRF tokens while
maintaining support for API token authentication.
2026-04-14 15:06:56 +03:00

140 lines
4.3 KiB
TypeScript

import { Project } from '../entities/Project';
import { handleAuthResponse } from './authUtils';
import { getApiPath } from '../config/paths';
import { getCsrfToken } from './csrfService';
export const fetchProjects = async (
stateFilter = 'all',
areaFilter = ''
): Promise<Project[]> => {
let url = 'projects';
const params = new URLSearchParams();
if (stateFilter !== 'all') params.append('state', stateFilter);
if (areaFilter) params.append('area', areaFilter);
if (params.toString()) url += `?${params.toString()}`;
const response = await fetch(getApiPath(url), {
credentials: 'include',
headers: { Accept: 'application/json' },
});
await handleAuthResponse(response, 'Failed to fetch projects.');
const data = await response.json();
return data.projects || data;
};
export const fetchGroupedProjects = async (
stateFilter = 'all',
areaFilter = ''
): Promise<Record<string, Project[]>> => {
let url = 'projects';
const params = new URLSearchParams();
params.append('grouped', 'true');
if (stateFilter !== 'all') params.append('state', stateFilter);
if (areaFilter) params.append('area', areaFilter);
if (params.toString()) url += `?${params.toString()}`;
const response = await fetch(getApiPath(url), {
credentials: 'include',
headers: { Accept: 'application/json' },
});
await handleAuthResponse(response, 'Failed to fetch projects.');
const data = await response.json();
return data;
};
export const fetchProjectById = async (projectId: string): Promise<Project> => {
const response = await fetch(getApiPath(`project/${projectId}`), {
credentials: 'include',
headers: { Accept: 'application/json' },
});
await handleAuthResponse(response, 'Failed to fetch project details.');
return await response.json();
};
export const createProject = async (
projectData: Partial<Project>
): Promise<Project> => {
const token = await getCsrfToken();
const response = await fetch(getApiPath('project'), {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'x-csrf-token': token,
},
body: JSON.stringify(projectData),
});
await handleAuthResponse(response, 'Failed to create project.');
return await response.json();
};
export const updateProject = async (
projectUid: string,
projectData: Partial<Project>
): Promise<Project> => {
const token = await getCsrfToken();
const response = await fetch(getApiPath(`project/${projectUid}`), {
method: 'PATCH',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'x-csrf-token': token,
},
body: JSON.stringify(projectData),
});
await handleAuthResponse(response, 'Failed to update project.');
return await response.json();
};
export const deleteProject = async (projectUid: string): Promise<void> => {
if (!projectUid || projectUid === null || projectUid === undefined) {
throw new Error('Cannot delete project: Invalid project UID');
}
console.log('Attempting to delete project with UID:', projectUid);
const token = await getCsrfToken();
const response = await fetch(getApiPath(`project/${projectUid}`), {
method: 'DELETE',
credentials: 'include',
headers: {
Accept: 'application/json',
'x-csrf-token': token,
},
});
console.log('Delete response status:', response.status);
if (!response.ok) {
const errorText = await response.text();
console.error('Delete failed with response:', errorText);
throw new Error(
`Failed to delete project: ${response.status} - ${errorText}`
);
}
await handleAuthResponse(response, 'Failed to delete project.');
};
export const fetchProjectBySlug = async (uidSlug: string): Promise<Project> => {
const response = await fetch(getApiPath(`project/${uidSlug}`), {
credentials: 'include',
headers: {
Accept: 'application/json',
},
});
await handleAuthResponse(response, 'Failed to fetch project.');
return await response.json();
};