feat(auth): add auth guard in hooks.server.ts with session validation

Validates session cookie via GET /v1/auth/me, populates event.locals
with benutzer and haushalt, redirects to /login if unauthenticated.
Public routes (/login, /register, /invite) bypass auth.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-02 13:19:40 +02:00
parent cfe38c39aa
commit 7a17873046
3 changed files with 161 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
import type { Handle } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';
import { apiClient } from '$lib/server/api';
const PUBLIC_ROUTES = ['/login', '/register', '/invite'];
function isPublicRoute(pathname: string): boolean {
return PUBLIC_ROUTES.some((route) => pathname === route || pathname.startsWith(route + '/'));
}
export const handle: Handle = async ({ event, resolve }) => {
if (isPublicRoute(event.url.pathname)) {
return resolve(event);
}
const sessionCookie = event.cookies.get('session');
if (!sessionCookie) {
redirect(302, '/login');
}
const api = apiClient(event.fetch);
const { data, error } = await api.GET('/v1/auth/me');
if (error || !data?.data) {
redirect(302, '/login');
}
const user = data.data;
event.locals.benutzer = {
id: user.id!,
name: user.displayName!,
rolle: user.householdRole as 'planer' | 'mitglied'
};
event.locals.haushalt = {
id: user.householdId!,
name: user.householdName!
};
return resolve(event);
};