import { fail, redirect } from '@sveltejs/kit'; import { dev } from '$app/environment'; import type { Actions, PageServerLoad } from './$types'; import { SESSION_COOKIE, createSession, findUserByEmail, verifyPassword } from '$lib/server/auth'; export const load: PageServerLoad = ({ locals }) => { if (locals.user) { throw redirect(303, '/admin'); } }; export const actions: Actions = { default: async ({ request, cookies }) => { const form = await request.formData(); const email = String(form.get('email') ?? '') .trim() .toLowerCase(); const password = String(form.get('password') ?? ''); if (!email || !password) { return fail(400, { error: 'Vnesite e-naslov in geslo.', email }); } const user = findUserByEmail(email); if (!user || !(await verifyPassword(user.passwordHash, password))) { return fail(400, { error: 'Napačen e-naslov ali geslo.', email }); } const { token, expiresAt } = createSession(user.id); cookies.set(SESSION_COOKIE, token, { path: '/', httpOnly: true, sameSite: 'lax', secure: !dev, expires: expiresAt }); throw redirect(303, '/admin'); } };