aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/hooks.server.js
blob: 39c89e98dc371118916ec7cdbf74f18da423dc8e (plain)
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
26
27
28
29
30
31
import { redirect } from '@sveltejs/kit';

const API = 'http://localhost:8080/api';

const PUBLIC_PREFIXES = ['/_app', '/api'];

export async function handle({ event, resolve }) {
	const isStatic = PUBLIC_PREFIXES.some((p) => event.url.pathname.startsWith(p));
	const isLogin = event.url.pathname === '/login';
	const isPublic = event.url.pathname === '/' || event.url.pathname.startsWith('/status/');

	if (isStatic || isLogin || isPublic) {
		return resolve(event);
	}

	if (event.url.pathname.startsWith('/admin')) {
		const token = event.cookies.get('auth_token');
		if (!token) {
			throw redirect(302, '/login');
		}
		const res = await fetch(`${API}/auth/verify`, {
			headers: { Authorization: `Bearer ${token}` }
		});
		if (!res.ok) {
			throw redirect(302, '/login');
		}
		event.locals.token = token;
	}

	return resolve(event);
}