Appends ?redirect= with the original pathname so the login page can redirect back after successful authentication. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import type { Handle } from '@sveltejs/kit';
|
|
import { redirect } from '@sveltejs/kit';
|
|
import { apiClient } from '$lib/server/api';
|
|
|
|
const PUBLIC_ROUTES = ['/login', '/register', '/invite'];
|
|
|
|
const STATIC_PREFIXES = ['/_app/', '/favicon'];
|
|
|
|
function isPublicRoute(pathname: string): boolean {
|
|
if (STATIC_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
|
|
return true;
|
|
}
|
|
return PUBLIC_ROUTES.some((route) => pathname === route || pathname.startsWith(route + '/'));
|
|
}
|
|
|
|
function loginRedirect(pathname: string): never {
|
|
const target = '/login?redirect=' + encodeURIComponent(pathname);
|
|
redirect(302, target);
|
|
}
|
|
|
|
export const handle: Handle = async ({ event, resolve }) => {
|
|
if (isPublicRoute(event.url.pathname)) {
|
|
return resolve(event);
|
|
}
|
|
|
|
const sessionCookie = event.cookies.get('session');
|
|
if (!sessionCookie) {
|
|
loginRedirect(event.url.pathname);
|
|
}
|
|
|
|
const api = apiClient(event.fetch);
|
|
const { data, error } = await api.GET('/v1/auth/me');
|
|
|
|
if (error || !data?.data) {
|
|
loginRedirect(event.url.pathname);
|
|
}
|
|
|
|
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);
|
|
};
|