Add API_KEYS_ACTIVE toggle to API key middleware

This commit is contained in:
NeilClack
2026-07-19 08:44:10 -05:00
parent cca26c0578
commit 74896234f9
+17 -14
View File
@@ -2,27 +2,30 @@ import { auth } from '$lib/auth';
import { svelteKitHandler } from 'better-auth/svelte-kit'; import { svelteKitHandler } from 'better-auth/svelte-kit';
import { building } from '$app/environment'; import { building } from '$app/environment';
import { validateApiKey } from '$lib/server/api-key'; import { validateApiKey } from '$lib/server/api-key';
import { env } from '$env/dynamic/private';
export async function handle({ event, resolve }) { export async function handle({ event, resolve }) {
if ( if (
event.url.pathname.startsWith('/api/v1/') && event.url.pathname.startsWith('/api/v1/') &&
!event.url.pathname.startsWith('/api/v1/automations/') !event.url.pathname.startsWith('/api/v1/automations/')
) { ) {
const authHeader = event.request.headers.get('authorization'); if (env.API_KEYS_ACTIVE !== 'false') {
if (!authHeader?.startsWith('Bearer ')) { const authHeader = event.request.headers.get('authorization');
return new Response(JSON.stringify({ error: 'API key required' }), { if (!authHeader?.startsWith('Bearer ')) {
status: 401, return new Response(JSON.stringify({ error: 'API key required' }), {
headers: { 'content-type': 'application/json' } status: 401,
}); headers: { 'content-type': 'application/json' }
} });
}
const key = authHeader.slice(7); const key = authHeader.slice(7);
const record = await validateApiKey(key); const record = await validateApiKey(key);
if (!record) { if (!record) {
return new Response(JSON.stringify({ error: 'Invalid or expired API key' }), { return new Response(JSON.stringify({ error: 'Invalid or expired API key' }), {
status: 401, status: 401,
headers: { 'content-type': 'application/json' } headers: { 'content-type': 'application/json' }
}); });
}
} }
return resolve(event); return resolve(event);