import { Session, getSessionFromStorage } from '@inrupt/solid-client-authn-node'; import { redirect, type Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { const pathname = event.url.pathname; if (pathname.match(/^\/solid\/login\/?$/)) { const session = new Session({ keepAlive: true }); event.cookies.set('sessionId', session.info.sessionId, { path: '/' }); const oidcIssuer = event.url.searchParams.get('oidcIssuer'); if (!oidcIssuer) throw new Error('No OIDC issuer provided'); return await session.login({ oidcIssuer, redirectUrl: `http://localhost:5173/solid/login/callback/`, clientName: 'Tabemono', handleRedirect: (url) => redirect(307, url) }); } if (pathname === '/solid/login/callback/') { const sessionId = event.cookies.get('sessionId'); if (!sessionId) throw new Error('No session ID'); const session = await getSessionFromStorage(sessionId); const url = `${event.url.origin}/solid/login/callback/${event.url.search}`; if (session) { const res = await session.handleIncomingRedirect(url); if (res?.isLoggedIn) return redirect(307, '/'); throw new Error('LOGIN ERROR'); } } if (pathname === '/solid/logout') { const sessionId = event.cookies.get('sessionId'); if (!sessionId) throw new Error('No session ID'); const session = await getSessionFromStorage(sessionId); session?.logout(); event.cookies.delete('sessionId', { path: '/' }); return redirect(307, '/exit'); } if (pathname === '/solid/fetch') { const resourceUrl = event.url.searchParams.get('resource'); if (!resourceUrl) throw new Error('No resource URL provided'); const sessionId = event.cookies.get('sessionId'); if (!sessionId) throw new Error('No session ID'); const session = await getSessionFromStorage(sessionId); return session?.fetch(resourceUrl); } // Provide session helper to event.locals event.locals.getSession = async () => { const sessionId = event.cookies.get('sessionId'); if (sessionId) return await getSessionFromStorage(sessionId); return undefined; }; const response = await resolve(event); return response; }; export default handle;