wireadmin/web/src/hooks.server.ts

28 lines
824 B
TypeScript
Raw Normal View History

2023-11-03 15:15:08 +00:00
import type { Handle } from '@sveltejs/kit';
import { verifyToken } from '$lib/auth';
import 'dotenv/config';
2023-11-03 15:15:08 +00:00
export const handle: Handle = async ({ event, resolve }) => {
const { HASHED_PASSWORD } = process.env;
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');
2023-11-04 12:05:45 +00:00
const token_valid = await verifyToken(token ?? '');
2023-11-03 15:15:08 +00:00
2023-11-04 12:05:45 +00:00
const redirect = new Response(null, { status: 302, headers: { location: '/login' } });
const is_login_page = event.url.pathname === '/login';
2023-11-03 15:15:08 +00:00
2023-11-04 12:05:45 +00:00
if (!token_valid && !is_login_page) {
2023-11-03 15:15:08 +00:00
return redirect;
}
2023-11-04 12:05:45 +00:00
if (token_valid && is_login_page) {
return new Response(null, { status: 302, headers: { location: '/' } });
}
2023-11-04 05:09:13 +00:00
}
2023-11-08 19:46:32 +00:00
return resolve(event);
2023-11-03 15:15:08 +00:00
};
2023-11-04 05:09:13 +00:00
2023-11-04 12:05:45 +00:00
const AUTH_EXCEPTION = ['/api/health'];