96 lines
2.4 KiB
JavaScript
96 lines
2.4 KiB
JavaScript
import { setError, setMessage, superValidate } from "sveltekit-superforms";
|
|
import { fail } from "@sveltejs/kit";
|
|
import { loginSchema, signupSchema } from "$lib/components/organisms/auth/schema";
|
|
import { zod } from "sveltekit-superforms/adapters";
|
|
import { db, usersTable } from "$lib/db";
|
|
import bcrypt from "bcrypt";
|
|
import * as authService from "$lib/services/auth.server";
|
|
import { eq } from "drizzle-orm";
|
|
import { hashPassword, validatePassword } from "$lib/utils/auth.utils";
|
|
/**
|
|
* @type {import("./$types").PageServerLoad}
|
|
*/
|
|
export const load = async () => {
|
|
return {
|
|
signupForm: await superValidate(zod(signupSchema)),
|
|
loginForm: await superValidate(zod(loginSchema)),
|
|
};
|
|
};
|
|
|
|
/**
|
|
* @type {import("@sveltejs/kit").Actions}
|
|
*/
|
|
export const actions = {
|
|
signup: async (event) => {
|
|
const form = await superValidate(event, zod(signupSchema));
|
|
if (!form.valid) {
|
|
return fail(400, {
|
|
form,
|
|
});
|
|
}
|
|
|
|
// await (async () => {
|
|
// return new Promise((res, rej) => {
|
|
// setTimeout(res, 5000)
|
|
// })
|
|
// })()
|
|
|
|
const newUser = await db.insert(usersTable).values({
|
|
name: form.data.name,
|
|
email: form.data.email,
|
|
hashed_password: (await hashPassword(form.data.password)),
|
|
}).returning({ id: usersTable.id }).onConflictDoNothing({ target: usersTable.email });
|
|
|
|
if (newUser.length === 0) return setError(form, "email", "Email already taken.", {
|
|
status: 409
|
|
});
|
|
|
|
const sessionId = await authService.createSession(newUser[0].id);
|
|
|
|
event.cookies.set("token", sessionId, {
|
|
path: "/",
|
|
expires: new Date("01-01-2025"),
|
|
secure: false
|
|
});
|
|
|
|
return {
|
|
form,
|
|
};
|
|
},
|
|
login: async (event) => {
|
|
const form = await superValidate(event, zod(loginSchema));
|
|
if (!form.valid) {
|
|
return fail(400, {
|
|
form,
|
|
});
|
|
}
|
|
|
|
// await (async () => {
|
|
// return new Promise((res, rej) => {
|
|
// setTimeout(res, 5000)
|
|
// })
|
|
// })()
|
|
|
|
const user = await db.select().from(usersTable).where(eq(usersTable.email, form.data.email));
|
|
|
|
if (user.length === 0) return setMessage(form, "Invalid login credentials", {
|
|
status: 409
|
|
});
|
|
|
|
if(!validatePassword(user[0].hashed_password, form.data.password)) return setMessage(form, "Invalid login credentials", {
|
|
status: 409
|
|
});
|
|
|
|
const sessionId = await authService.createSession(user[0].id);
|
|
|
|
event.cookies.set("token", sessionId, {
|
|
path: "/",
|
|
expires: new Date("01-01-2025"),
|
|
secure: false
|
|
});
|
|
|
|
return {
|
|
form,
|
|
};
|
|
},
|
|
}; |