wireadmin/web/src/hooks.server.ts

34 lines
1.0 KiB
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
console.log('handle', event.url.pathname, 'invalid token');
return redirect;
}
2023-11-04 12:05:45 +00:00
if (token_valid && is_login_page) {
console.log('handle', 'already logged in');
return new Response(null, { status: 302, headers: { location: '/' } });
}
2023-11-04 05:09:13 +00:00
}
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
2023-11-04 12:05:45 +00:00
const AUTH_EXCEPTION = ['/api/health'];