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.
139 lines
4.1 KiB
TypeScript
139 lines
4.1 KiB
TypeScript
import { getApiPath } from '../config/paths';
|
|
import { Task } from '../entities/Task';
|
|
import { getCsrfToken } from './csrfService';
|
|
|
|
export interface HabitCompletion {
|
|
id: number;
|
|
task_id: number;
|
|
completed_at: string;
|
|
original_due_date: string;
|
|
skipped: boolean;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export async function fetchHabits(): Promise<Task[]> {
|
|
const response = await fetch(getApiPath('habits'), {
|
|
credentials: 'include',
|
|
});
|
|
if (!response.ok) throw new Error('Failed to fetch habits');
|
|
const data = await response.json();
|
|
return data.habits;
|
|
}
|
|
|
|
export async function createHabit(habitData: Partial<Task>): Promise<Task> {
|
|
const response = await fetch(getApiPath('habits'), {
|
|
method: 'POST',
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-csrf-token': await getCsrfToken(),
|
|
},
|
|
body: JSON.stringify(habitData),
|
|
});
|
|
if (!response.ok) throw new Error('Failed to create habit');
|
|
const data = await response.json();
|
|
return data.habit;
|
|
}
|
|
|
|
export async function logHabitCompletion(habitUid: string, completedAt?: Date) {
|
|
const response = await fetch(getApiPath(`habits/${habitUid}/complete`), {
|
|
method: 'POST',
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-csrf-token': await getCsrfToken(),
|
|
},
|
|
body: JSON.stringify({
|
|
completed_at: completedAt?.toISOString(),
|
|
}),
|
|
});
|
|
if (!response.ok) throw new Error('Failed to log completion');
|
|
return response.json();
|
|
}
|
|
|
|
export async function fetchHabitStats(
|
|
habitUid: string,
|
|
startDate?: Date,
|
|
endDate?: Date
|
|
) {
|
|
const params = new URLSearchParams();
|
|
if (startDate) params.append('start_date', startDate.toISOString());
|
|
if (endDate) params.append('end_date', endDate.toISOString());
|
|
|
|
const response = await fetch(
|
|
getApiPath(`habits/${habitUid}/stats?${params}`),
|
|
{
|
|
credentials: 'include',
|
|
}
|
|
);
|
|
if (!response.ok) throw new Error('Failed to fetch stats');
|
|
return response.json();
|
|
}
|
|
|
|
export async function updateHabit(
|
|
habitUid: string,
|
|
updates: Partial<Task>
|
|
): Promise<Task> {
|
|
const response = await fetch(getApiPath(`habits/${habitUid}`), {
|
|
method: 'PUT',
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-csrf-token': await getCsrfToken(),
|
|
},
|
|
body: JSON.stringify(updates),
|
|
});
|
|
if (!response.ok) throw new Error('Failed to update habit');
|
|
const data = await response.json();
|
|
return data.habit;
|
|
}
|
|
|
|
export async function deleteHabit(habitUid: string): Promise<void> {
|
|
const response = await fetch(getApiPath(`habits/${habitUid}`), {
|
|
method: 'DELETE',
|
|
credentials: 'include',
|
|
headers: {
|
|
'x-csrf-token': await getCsrfToken(),
|
|
},
|
|
});
|
|
if (!response.ok) throw new Error('Failed to delete habit');
|
|
}
|
|
|
|
export async function fetchHabitCompletions(
|
|
habitUid: string,
|
|
startDate?: Date,
|
|
endDate?: Date
|
|
): Promise<HabitCompletion[]> {
|
|
const params = new URLSearchParams();
|
|
if (startDate) params.append('start_date', startDate.toISOString());
|
|
if (endDate) params.append('end_date', endDate.toISOString());
|
|
|
|
const response = await fetch(
|
|
getApiPath(`habits/${habitUid}/completions?${params}`),
|
|
{
|
|
credentials: 'include',
|
|
}
|
|
);
|
|
if (!response.ok) throw new Error('Failed to fetch completions');
|
|
const data = await response.json();
|
|
return data.completions;
|
|
}
|
|
|
|
export async function deleteHabitCompletion(
|
|
habitUid: string,
|
|
completionId: number
|
|
): Promise<{ task: Task }> {
|
|
const response = await fetch(
|
|
getApiPath(`habits/${habitUid}/completions/${completionId}`),
|
|
{
|
|
method: 'DELETE',
|
|
credentials: 'include',
|
|
headers: {
|
|
'x-csrf-token': await getCsrfToken(),
|
|
},
|
|
}
|
|
);
|
|
if (!response.ok) throw new Error('Failed to delete completion');
|
|
return response.json();
|
|
}
|