2025-11-24 01:00:50 +01:00
|
|
|
import { getSessionData } from '$lib/utils/services/auth/session';
|
2026-03-22 18:42:23 +01:00
|
|
|
import { getHasCioCookies } from '$lib/utils/functions/cookies';
|
2026-03-18 23:39:12 +01:00
|
|
|
import { applyCspExtensions } from '$lib/utils/csp';
|
2025-11-24 01:00:50 +01:00
|
|
|
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
|
|
|
|
2025-11-24 01:00:50 +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
|
|
|
|
2025-11-24 01:00:50 +01:00
|
|
|
if (sessionData) {
|
|
|
|
|
event.locals = sessionData;
|
|
|
|
|
}
|
2025-01-09 01:30:01 +01:00
|
|
|
|
2026-03-18 23:39:12 +01:00
|
|
|
let response: Response;
|
|
|
|
|
|
2025-11-24 01:00:50 +01:00
|
|
|
if (event.url.pathname.includes('/api')) {
|
2026-03-18 23:39:12 +01:00
|
|
|
response = await handleAPIRoutes(args);
|
|
|
|
|
} else {
|
|
|
|
|
response = await handlePagesRoutes(args);
|
2025-11-24 01:00:50 +01:00
|
|
|
}
|
2025-01-09 01:30:01 +01:00
|
|
|
|
2026-03-18 23:39:12 +01:00
|
|
|
return applyCspExtensions(response);
|
2025-11-24 01:00:50 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handlePagesRoutes: Handle = async ({ event, resolve }) => {
|
2025-01-09 01:30:01 +01:00
|
|
|
const { pathname } = event.url;
|
2026-03-22 18:42:23 +01:00
|
|
|
const hasCioCookie = getHasCioCookies(event.cookies);
|
2025-01-09 01:30:01 +01:00
|
|
|
|
|
|
|
|
if (isPublicRoute(pathname)) {
|
2025-11-24 01:00:50 +01:00
|
|
|
return resolve(event);
|
2025-01-09 01:30:01 +01:00
|
|
|
}
|
|
|
|
|
|
2026-03-28 11:50:53 +01:00
|
|
|
if (!event?.locals?.user && !hasCioCookie) {
|
2026-03-12 08:57:39 +01:00
|
|
|
console.log('no user and no cio cookie, redirecting to login');
|
2025-11-24 01:00:50 +01:00
|
|
|
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
|
|
|
|
2025-11-24 01:00:50 +01:00
|
|
|
return redirect(303, redirectPath);
|
2025-08-30 08:00:25 +01:00
|
|
|
}
|
2025-01-09 01:30:01 +01:00
|
|
|
|
2025-11-24 01:00:50 +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
|
|
|
};
|