tududi/frontend/utils/notesService.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

103 lines
3.4 KiB
TypeScript

import { Note } from '../entities/Note';
import {
handleAuthResponse,
getDefaultHeaders,
getPostHeadersWithCsrf,
} from './authUtils';
import { getApiPath } from '../config/paths';
export const fetchNotes = async (): Promise<Note[]> => {
const response = await fetch(getApiPath('notes'), {
credentials: 'include',
headers: {
...getDefaultHeaders(),
'Cache-Control': 'no-cache',
},
cache: 'no-store',
});
await handleAuthResponse(response, 'Failed to fetch notes.');
return await response.json();
};
export const createNote = async (noteData: Note): Promise<Note> => {
// Transform project_id to project_uid if needed (same as updateNote)
const requestData = { ...noteData };
if (noteData.project && noteData.project.uid) {
requestData.project_uid = noteData.project.uid;
} else if (noteData.project_uid) {
// project_uid is already set, use it as-is
} else if (noteData.project_id && !noteData.project_uid) {
// Legacy: if only project_id is provided, we can't convert it to uid here
// This should not happen with the new implementation, but keeping for safety
console.warn(
'Note creation with project_id but no project_uid - this may fail'
);
}
const response = await fetch(getApiPath('note'), {
method: 'POST',
credentials: 'include',
headers: await getPostHeadersWithCsrf(),
body: JSON.stringify(requestData),
});
await handleAuthResponse(response, 'Failed to create note.');
return await response.json();
};
export const updateNote = async (
noteUid: string,
noteData: Note
): Promise<Note> => {
// Transform project_id to project_uid if needed
const requestData = { ...noteData };
if (noteData.project && noteData.project.uid) {
requestData.project_uid = noteData.project.uid;
} else if (noteData.project_uid) {
// project_uid is already set, use it as-is
} else if (noteData.project_id && !noteData.project_uid) {
// Legacy: if only project_id is provided, we can't convert it to uid here
// This should not happen with the new implementation, but keeping for safety
console.warn(
'Note update with project_id but no project_uid - this may fail'
);
}
// Use the provided noteUid
const noteIdentifier = noteUid;
const response = await fetch(getApiPath(`note/${noteIdentifier}`), {
method: 'PATCH',
credentials: 'include',
headers: await getPostHeadersWithCsrf(),
body: JSON.stringify(requestData),
});
await handleAuthResponse(response, 'Failed to update note.');
return await response.json();
};
export const deleteNote = async (noteUid: string): Promise<void> => {
const response = await fetch(getApiPath(`note/${noteUid}`), {
method: 'DELETE',
credentials: 'include',
headers: await getPostHeadersWithCsrf(),
});
await handleAuthResponse(response, 'Failed to delete note.');
};
export const fetchNoteBySlug = async (uidSlug: string): Promise<Note> => {
const response = await fetch(getApiPath(`note/${uidSlug}`), {
credentials: 'include',
headers: {
...getDefaultHeaders(),
'Cache-Control': 'no-cache',
},
cache: 'no-store',
});
await handleAuthResponse(response, 'Failed to fetch note.');
return await response.json();
};