aboutsummaryrefslogtreecommitdiffstats
path: root/src/hooks/index.js
blob: 2284d88dc77fddd771b9d8f62f1eaa9cff45f83c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import cookie from 'cookie';
import { get } from '$lib/utils';
import { protectedRoutes } from '$lib/utils';

export async function handle({ event, resolve }) {
	let {
		params,
		request: { headers }
	} = event;

	const cookies = cookie.parse(headers.get('cookie') || '');
	let { token } = cookies;
	event.locals = { token };

	if (protectedRoutes.find((p) => event.url.pathname.match(p))) {
		let user = await get('/me', { accept: 'application/json', authorization: `Bearer ${token}` });
		if (user.username !== params.username) throw new Error('user not found');
	}

	return resolve(event);
}

export const getSession = ({ locals: { token } }) => {
	return { token };
};