all repos — tabemono @ 84c83e23ec2cdd455d117d9fe7a08a11c9e3a600

src/hooks.server.ts (view raw)

 1import { Session, getSessionFromStorage } from '@inrupt/solid-client-authn-node';
 2import { redirect, type Handle } from '@sveltejs/kit';
 3
 4export const handle: Handle = async ({ event, resolve }) => {
 5	const pathname = event.url.pathname;
 6
 7	if (pathname.match(/^\/solid\/login\/?$/)) {
 8		const session = new Session({ keepAlive: true });
 9		event.cookies.set('sessionId', session.info.sessionId, { path: '/' });
10		const oidcIssuer = event.url.searchParams.get('oidcIssuer');
11		if (!oidcIssuer) throw new Error('No OIDC issuer provided');
12		return await session.login({
13			oidcIssuer,
14			redirectUrl: `http://localhost:5173/solid/login/callback/`,
15			clientName: 'Tabemono',
16			handleRedirect: (url) => redirect(307, url)
17		});
18	}
19
20	if (pathname === '/solid/login/callback/') {
21		const sessionId = event.cookies.get('sessionId');
22		if (!sessionId) throw new Error('No session ID');
23		const session = await getSessionFromStorage(sessionId);
24		const url = `${event.url.origin}/solid/login/callback/${event.url.search}`;
25		if (session) {
26			const res = await session.handleIncomingRedirect(url);
27			if (res?.isLoggedIn) return redirect(307, '/');
28			throw new Error('LOGIN ERROR');
29		}
30	}
31
32	if (pathname === '/solid/logout') {
33		const sessionId = event.cookies.get('sessionId');
34		if (!sessionId) throw new Error('No session ID');
35		const session = await getSessionFromStorage(sessionId);
36		session?.logout();
37		event.cookies.delete('sessionId', { path: '/' });
38		return redirect(307, '/exit');
39	}
40
41	if (pathname === '/solid/fetch') {
42		const resourceUrl = event.url.searchParams.get('resource');
43		if (!resourceUrl) throw new Error('No resource URL provided');
44		const sessionId = event.cookies.get('sessionId');
45		if (!sessionId) throw new Error('No session ID');
46		const session = await getSessionFromStorage(sessionId);
47		console.log('FETCH POD RESOURCE ', resourceUrl);
48		return session?.fetch(resourceUrl);
49	}
50
51	// Provide session helper to event.locals
52	event.locals.getSession = async () => {
53		const sessionId = event.cookies.get('sessionId');
54		if (sessionId) return await getSessionFromStorage(sessionId);
55		return undefined;
56	};
57
58	const response = await resolve(event);
59	return response;
60};
61
62export default handle;