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
33
34
35
36
37
38
39
|
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: { dbConn } }) => {
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(dbConn, 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(dbConn, 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;
|