2023-11-03 15:15:08 +00:00
|
|
|
import type { Handle } from '@sveltejs/kit';
|
|
|
|
import { verifyToken } from '$lib/auth';
|
2023-11-04 05:09:13 +00:00
|
|
|
import { HASHED_PASSWORD } from '$env/static/private';
|
2023-11-03 15:15:08 +00:00
|
|
|
|
|
|
|
export const handle: Handle = async ({ event, resolve }) => {
|
|
|
|
|
2023-11-04 05:09:13 +00:00
|
|
|
if (!!HASHED_PASSWORD && !AUTH_EXCEPTION.includes(event.url.pathname)) {
|
2023-11-03 15:15:08 +00:00
|
|
|
const token = event.cookies.get('authorization');
|
|
|
|
const redirect = new Response(null, { status: 302, headers: { location: '/login' } });
|
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
console.log('handle', event.url.pathname, 'no token');
|
|
|
|
return redirect;
|
|
|
|
}
|
|
|
|
|
|
|
|
const token_valid = await verifyToken(token);
|
|
|
|
if (!token_valid) {
|
|
|
|
console.log('handle', event.url.pathname, 'invalid token');
|
|
|
|
return redirect;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-04 05:09:13 +00:00
|
|
|
if (event.url.pathname === '/login') {
|
|
|
|
console.log('handle', 'already logged in');
|
|
|
|
return new Response(null, { status: 302, headers: { location: '/' } });
|
|
|
|
}
|
|
|
|
|
2023-11-03 15:15:08 +00:00
|
|
|
const resp = await resolve(event);
|
|
|
|
|
|
|
|
console.log('handle', event.url.pathname, resp.status);
|
|
|
|
|
|
|
|
return resp;
|
|
|
|
};
|
2023-11-04 05:09:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
const AUTH_EXCEPTION = ['/api/health', '/login'];
|