diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 87c1f1d..27be638 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -12,19 +12,42 @@ import { initializeScheduler } from "./lib/server/scheduler" initializeScheduler(); async function authorization({ event, resolve }) { - // Protect any routes under /authenticated + const session = await event.locals.auth(); + + // Protect rezepte routes if (event.url.pathname.startsWith('/rezepte/edit') || event.url.pathname.startsWith('/rezepte/add')) { - const session = await event.locals.auth(); if (!session) { // Preserve the original URL the user was trying to access const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search); redirect(303, `/login?callbackUrl=${callbackUrl}`); } - else if (! session.user.groups.includes('rezepte_users')) { - // strip last dir from url - // TODO: give indication of why access failed - const new_url = event.url.pathname.split('/').slice(0, -1).join('/'); - redirect(303, new_url); + else if (!session.user.groups.includes('rezepte_users')) { + error(403, { + message: 'Zugriff verweigert', + details: 'Du hast keine Berechtigung für diesen Bereich. Falls du glaubst, dass dies ein Fehler ist, wende dich bitte an Alexander.' + }); + } + } + + // Protect cospend routes and API endpoints + if (event.url.pathname.startsWith('/cospend') || event.url.pathname.startsWith('/api/cospend')) { + if (!session) { + // For API routes, return 401 instead of redirecting + if (event.url.pathname.startsWith('/api/cospend')) { + error(401, { + message: 'Anmeldung erforderlich', + details: 'Du musst angemeldet sein, um auf diesen Bereich zugreifen zu können.' + }); + } + // For page routes, redirect to login + const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search); + redirect(303, `/login?callbackUrl=${callbackUrl}`); + } + else if (!session.user.groups.includes('cospend')) { + error(403, { + message: 'Zugriff verweigert', + details: 'Du hast keine Berechtigung für diesen Bereich. Falls du glaubst, dass dies ein Fehler ist, wende dich bitte an Alexander.' + }); } }