bw-hspc-contest-env/web/src/hooks.server.ts

55 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-04-28 13:42:16 -04:00
import { redirect, type Handle } from '@sveltejs/kit';
2023-08-26 11:07:09 -04:00
import { PrismaClient } from '@prisma/client';
2023-05-01 13:26:49 -04:00
import { startGitServer } from '$lib/server/gitserver';
2023-08-26 11:07:09 -04:00
import { hashPassword, isSessionValid, logout } from '$lib/server/auth';
2023-05-01 13:26:49 -04:00
2023-08-26 11:07:09 -04:00
async function createDefaultAccount(db: PrismaClient) {
const count = await db.user.count();
if (count !== 0) {
return;
}
const password = await hashPassword('bw123');
await db.user.create({
data: { username: 'admin', passwordHash: password.hash, passwordSalt: password.salt }
});
2023-04-28 13:42:16 -04:00
}
2023-10-15 14:17:45 -04:00
if (process.env.INIT !== undefined && process.env.INIT === 'true') {
console.log('Runtime initialization...');
2023-08-26 11:07:09 -04:00
const db = new PrismaClient();
createDefaultAccount(db);
2023-10-15 14:17:45 -04:00
startGitServer();
2023-04-28 13:42:16 -04:00
}
export const handle = (async ({ event, resolve }) => {
2023-08-26 11:41:37 -04:00
const theme = event.cookies.get('theme') as 'light' | 'dark' | undefined;
event.locals.theme = theme ?? 'dark';
2023-05-06 00:01:27 -04:00
if (event.request.method === 'OPTIONS') {
return new Response('ok', {
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
}
});
}
2023-04-28 13:42:16 -04:00
if (event.url.pathname.startsWith('/login')) {
2023-08-26 11:07:09 -04:00
if ((await isSessionValid(event.cookies)) === true) {
2023-12-19 16:58:34 -05:00
redirect(302, '/admin');
2023-04-28 13:42:16 -04:00
}
}
if (event.url.pathname.startsWith('/admin')) {
2023-08-26 11:07:09 -04:00
if ((await isSessionValid(event.cookies)) !== true) {
logout(event.cookies);
2023-12-19 16:58:34 -05:00
redirect(302, '/login');
2023-04-28 13:42:16 -04:00
}
}
2023-08-26 11:41:37 -04:00
const res = await resolve(event, {
transformPageChunk: ({ html }) => html.replace('%theme%', event.locals.theme)
});
2023-04-28 13:42:16 -04:00
return res;
}) satisfies Handle;