src/routes/login/+page.server.ts 1.2 K raw
1
import type { Actions, PageServerLoad } from "./$types";
2
import { fail, redirect } from "@sveltejs/kit";
3
import { verifyPassword, createSession } from "$lib";
4
5
export const load: PageServerLoad = async ({ locals }) => {
6
	if (locals.user?.authenticated) {
7
		throw redirect(302, "/admin");
8
	}
9
	return {};
10
};
11
12
export const actions: Actions = {
13
	default: async ({ request, platform, cookies }) => {
14
		const data = await request.formData();
15
		const password = data.get("password");
16
17
		if (!password || typeof password !== "string") {
18
			return fail(400, { error: "Password is required" });
19
		}
20
21
		const secret = platform?.env?.SESSION_SECRET;
22
		const passwordHash = platform?.env?.ADMIN_PASSWORD_HASH;
23
24
		if (!secret || !passwordHash) {
25
			return fail(500, { error: "Server configuration error" });
26
		}
27
28
		const isValid = await verifyPassword(password, passwordHash, secret);
29
30
		if (!isValid) {
31
			return fail(401, { error: "Invalid password" });
32
		}
33
34
		const session = await createSession(secret);
35
36
		cookies.set("session", session, {
37
			path: "/",
38
			httpOnly: true,
39
			secure: true,
40
			sameSite: "strict",
41
			maxAge: 60 * 60 * 24, // 24 hours
42
		});
43
44
		throw redirect(302, "/admin");
45
	},
46
};