import { getUser } from "$lib/server/users"; import { createSession } from "$lib/server/sessions"; import { fail, redirect } from "@sveltejs/kit"; import type { Actions } from "./$types"; export const actions = { default: async ({ url, cookies, request, locals: { dbClient: dbClient } }) => { const formData = Object.fromEntries(await request.formData()) as { email?: string; password?: string; }; if (!formData.email || !formData.password) { return fail(400, { failure: true, error: "Du skal udfylde alle felterne!" }); } const user = await getUser(dbClient, formData.email, formData.password); if (!user) { // It's important that we don't leak _which_ value is missing. return fail(404, { failure: true, error: "Forkert email/kodeord kombi!" }); } console.debug("Found user %o", user); // The user has proven that they posses the right credentials. In return they gain a session token, which can be used to authenticate future requests. const session = await createSession(dbClient, user.id); cookies.set("SESSION_ID", session.token, { path: "/", secure: true, sameSite: "strict", }); console.debug("Created session %o", session); // If sent here from trying to access another page without session cookie. if (url.searchParams.has("redirectTo")) { return redirect(303, url.searchParams.get("redirectTo")!); } return { success: true }; }, } satisfies Actions;