try refactor auth

This commit is contained in:
overcuriousity
2025-07-24 00:26:01 +02:00
parent 0ac31484d5
commit 32fca8a06f
10 changed files with 236 additions and 135 deletions

View File

@@ -1,6 +1,6 @@
// src/pages/api/ai/query.ts
import type { APIRoute } from 'astro';
import { getSessionFromRequest, verifySession } from '../../../utils/auth.js';
import { withAPIAuth, createAuthErrorResponse } from '../../../utils/auth.js';
import { getCompressedToolsDataForAI } from '../../../utils/dataService.js';
export const prerender = false;
@@ -275,30 +275,13 @@ Antworte NUR mit validen JSON. Keine zusätzlichen Erklärungen außerhalb des J
export const POST: APIRoute = async ({ request }) => {
try {
// Check if authentication is required
const authRequired = process.env.AUTHENTICATION_NECESSARY !== 'false';
let userId = 'test-user';
if (authRequired) {
// Authentication check
const sessionToken = getSessionFromRequest(request);
if (!sessionToken) {
return new Response(JSON.stringify({ error: 'Authentication required' }), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
const session = await verifySession(sessionToken);
if (!session) {
return new Response(JSON.stringify({ error: 'Invalid session' }), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
userId = session.userId;
// CONSOLIDATED: Replace 20+ lines with single function call
const authResult = await withAPIAuth(request);
if (!authResult.authenticated) {
return createAuthErrorResponse();
}
const userId = authResult.userId;
// Rate limiting
if (!checkRateLimit(userId)) {