boredgame/src/routes/(auth)/login/+page.server.ts

101 lines
2.7 KiB
TypeScript
Raw Normal View History

import { fail, type Actions } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
import { zod } from 'sveltekit-superforms/adapters';
2023-05-21 05:18:04 +00:00
import { setError, superValidate } from 'sveltekit-superforms/server';
import { redirect } from 'sveltekit-flash-message/server';
import { lucia } from '$lib/server/auth';
import { Argon2id } from 'oslo/password';
2024-02-08 03:37:54 +00:00
import db from '$lib/drizzle';
import { signInSchema } from '$lib/validations/auth'
2024-02-08 03:37:54 +00:00
import { collections, users, wishlists } from '../../../schema';
import type { PageServerLoad } from './$types';
2023-05-21 05:18:04 +00:00
export const load: PageServerLoad = async (event) => {
const form = await superValidate(event, zod(signInSchema));
console.log('login load event', event);
if (event.locals.user) {
const message = { type: 'info', message: 'You are already signed in' } as const;
throw redirect('/', message, event);
}
return {
form
};
2023-05-21 05:18:04 +00:00
};
export const actions: Actions = {
2023-05-21 05:18:04 +00:00
default: async (event) => {
const { locals } = event;
const form = await superValidate(event, zod(signInSchema));
2023-05-21 05:18:04 +00:00
if (!form.valid) {
form.data.password = '';
2023-05-21 05:18:04 +00:00
return fail(400, {
form
});
}
let session;
let sessionCookie;
2023-05-21 05:18:04 +00:00
try {
const password = form.data.password;
2024-02-08 03:37:54 +00:00
const user = await db.query.users.findFirst({
where: eq(users.username, form.data.username)
});
console.log('user', JSON.stringify(user, null, 2));
if (!user || !user.hashed_password) {
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
}
const validPassword = await new Argon2id().verify(user.hashed_password, password);
if (!validPassword) {
console.log('invalid password');
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
}
await db
.insert(collections)
.values({
user_id: user.id
})
.onConflictDoNothing();
await db
.insert(wishlists)
.values({
user_id: user.id
})
.onConflictDoNothing();
console.log('ip', locals.ip);
console.log('country', locals.country);
session = await lucia.createSession(user.id, {
ip_country: locals.country,
ip_address: locals.ip
});
sessionCookie = lucia.createSessionCookie(session.id);
2023-05-21 05:18:04 +00:00
} catch (e) {
// TODO: need to return error message to the client
console.error(e);
form.data.password = '';
return setError(form, '', 'Your username or password is incorrect.');
2023-05-21 05:18:04 +00:00
}
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
...sessionCookie.attributes
});
form.data.username = '';
form.data.password = '';
const message = { type: 'success', message: 'Signed In!' };
// return { form, message };
throw redirect('/', message, event);
2023-05-21 05:18:04 +00:00
}
};