import { redirect } from '@sveltejs/kit'; import type { RequestEvent } from '@sveltejs/kit'; /** * Reusable authentication check helper. * Throws a redirect to /login if the user is not authenticated. * Returns the authenticated user from event.locals. * * For API routes, also checks for Bearer token in Authorization header. * If a valid API token is found, the user is set from the token's owner. */ export function requireAuth(event: RequestEvent) { const user = event.locals.user; if (!user) { // For API routes, redirect is not appropriate — but we keep the behavior // consistent with the existing codebase. The hooks.server.ts handles // API token validation and sets event.locals.user before routes run. throw redirect(302, '/login'); } return user; } /** * Check if the current request has an authenticated user without redirecting. */ export function isAuthenticated(event: RequestEvent): boolean { return event.locals.user !== null; } /** * Extract Bearer token from Authorization header, if present. * Returns the token string or null. */ export function extractBearerToken(event: RequestEvent): string | null { const authHeader = event.request.headers.get('authorization'); if (!authHeader) { return null; } const parts = authHeader.split(' '); if (parts.length !== 2 || parts[0] !== 'Bearer') { return null; } return parts[1]; }