Files
portfolio/app/api/auth/validate/route.ts
denshooter 9072faae43 refactor: enhance security and performance in configuration and API routes
- Update Content Security Policy (CSP) in next.config.ts to avoid `unsafe-eval` in production, improving security against XSS attacks.
- Refactor API routes to enforce admin authentication and session validation, ensuring secure access to sensitive endpoints.
- Optimize analytics data retrieval by using database aggregation instead of loading all records into memory, improving performance and reducing memory usage.
- Implement session token creation and verification for better session management and security across the application.
- Enhance error handling and input validation in various API routes to ensure robustness and prevent potential issues.
2026-01-11 22:44:26 +01:00

51 lines
1.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { verifySessionToken } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
const { sessionToken, csrfToken } = await request.json();
if (!sessionToken) {
return new NextResponse(
JSON.stringify({ valid: false, error: 'No session token provided' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
// CSRF Protection
const expectedCSRF = request.headers.get('x-csrf-token');
if (!csrfToken || !expectedCSRF || csrfToken !== expectedCSRF) {
return new NextResponse(
JSON.stringify({ valid: false, error: 'CSRF token validation failed' }),
{ status: 403, headers: { 'Content-Type': 'application/json' } }
);
}
const valid = verifySessionToken(request, sessionToken);
if (!valid) {
return new NextResponse(
JSON.stringify({ valid: false, error: 'Session expired or invalid' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
return new NextResponse(
JSON.stringify({ valid: true, message: 'Session valid' }),
{
status: 200,
headers: {
'Content-Type': 'application/json',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block'
}
}
);
} catch {
return new NextResponse(
JSON.stringify({ valid: false, error: 'Internal server error' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
}