Files
classroomio/apps/dashboard/src/hooks.server.ts
T

59 lines
1.6 KiB
TypeScript
Raw Normal View History

import { getSessionData } from '$lib/utils/services/auth/session';
2026-03-12 08:57:39 +01:00
import { getCioCookieString } from '$lib/utils/functions/cookies';
import { type Handle, redirect } from '@sveltejs/kit';
import { isPublicApiRoute, isPublicRoute } from '$lib/utils/functions/routes/isPublicRoute';
import { ROUTE } from '$lib/utils/constants/routes';
2025-01-09 01:30:01 +01:00
export const handle: Handle = async (args) => {
const { event } = args;
const sessionData = await getSessionData(event.cookies);
2025-01-09 01:30:01 +01:00
if (sessionData) {
event.locals = sessionData;
}
2025-01-09 01:30:01 +01:00
// Handle API routes
if (event.url.pathname.includes('/api')) {
return handleAPIRoutes(args);
}
2025-01-09 01:30:01 +01:00
// Handle other routes (ui pages, etc.)
return handlePagesRoutes(args);
};
const handlePagesRoutes: Handle = async ({ event, resolve }) => {
2025-01-09 01:30:01 +01:00
const { pathname } = event.url;
2026-03-12 08:57:39 +01:00
const hasCioCookie = Boolean(getCioCookieString(event.cookies));
2025-01-09 01:30:01 +01:00
if (isPublicRoute(pathname)) {
return resolve(event);
2025-01-09 01:30:01 +01:00
}
2026-03-12 08:57:39 +01:00
if (!event.locals.user && !hasCioCookie) {
console.log('no user and no cio cookie, redirecting to login');
const shouldAddRedirectParam = !pathname.includes(ROUTE.LOGOUT);
2026-03-09 11:18:22 +01:00
const fullPath = pathname + event.url.search;
const redirectPath = shouldAddRedirectParam
? `${ROUTE.LOGIN}?redirect=${encodeURIComponent(fullPath)}`
: ROUTE.LOGIN;
2025-01-09 01:30:01 +01:00
return redirect(303, redirectPath);
}
2025-01-09 01:30:01 +01:00
return resolve(event);
};
const handleAPIRoutes: Handle = async ({ event, resolve }) => {
const { pathname } = event.url;
if (isPublicApiRoute(pathname)) {
return resolve(event);
}
if (!event.locals.user) {
redirect(303, '/login');
}
return resolve(event);
2025-01-09 01:30:01 +01:00
};