aboutsummaryrefslogtreecommitdiff
path: root/src/routes/login/+page.server.ts
blob: b43c97e5e9a02994df965e6f59339b9d70debd24 (plain) (blame)
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
32

import { fail, redirect } from '@sveltejs/kit';
import { setSession, verifyPassword } from '$lib/server/auth';
import type { Actions, PageServerLoad } from './$types';

function safeNext(value: string | null): string {
	return value?.startsWith('/') && !value.startsWith('//')
		? value
		: '/groceries';
}

export const load: PageServerLoad = ({ url }) => ({
	next: safeNext(url.searchParams.get('next')),
});

export const actions: Actions = {
	default: async ({ request, cookies, url }) => {
		const data = await request.formData();
		const password = data.get('password')?.toString() ?? '';
		const next = safeNext(
			data.get('next')?.toString() ?? url.searchParams.get('next'),
		);

		if (!verifyPassword(password)) {
			console.warn('[auth] failed login attempt');
			return fail(401, { error: 'Mot de passe incorrect', next });
		}

		console.info('[auth] login succeeded');
		setSession(cookies, url.protocol === 'https:');
		throw redirect(303, next);
	},
};