2023-05-21 05:18:04 +00:00
|
|
|
import { fail, redirect } from '@sveltejs/kit';
|
|
|
|
|
import { setError, superValidate } from 'sveltekit-superforms/server';
|
|
|
|
|
import { auth } from '$lib/server/lucia';
|
2023-06-16 06:28:49 +00:00
|
|
|
import prisma from '$lib/prisma.js';
|
2023-05-21 05:18:04 +00:00
|
|
|
import { userSchema } from '$lib/config/zod-schemas';
|
|
|
|
|
|
|
|
|
|
const signInSchema = userSchema.pick({
|
|
|
|
|
username: true,
|
|
|
|
|
password: true
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const load = async (event) => {
|
|
|
|
|
const session = await event.locals.auth.validate();
|
|
|
|
|
if (session) {
|
|
|
|
|
throw redirect(302, '/');
|
|
|
|
|
}
|
2023-06-16 06:28:49 +00:00
|
|
|
const form = await superValidate(event, signInSchema);
|
|
|
|
|
return {
|
|
|
|
|
form
|
|
|
|
|
};
|
2023-05-21 05:18:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const actions = {
|
|
|
|
|
default: async (event) => {
|
|
|
|
|
const form = await superValidate(event, signInSchema);
|
|
|
|
|
|
|
|
|
|
if (!form.valid) {
|
2023-05-29 06:34:39 +00:00
|
|
|
form.data.password = '';
|
2023-05-21 05:18:04 +00:00
|
|
|
return fail(400, {
|
|
|
|
|
form
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const key = await auth.useKey('username', form.data.username, form.data.password);
|
|
|
|
|
const session = await auth.createSession(key.userId);
|
|
|
|
|
event.locals.auth.setSession(session);
|
2023-06-16 06:28:49 +00:00
|
|
|
|
|
|
|
|
const user = await prisma.authUser.findUnique({
|
|
|
|
|
where: {
|
|
|
|
|
id: session.userId
|
|
|
|
|
},
|
|
|
|
|
include: {
|
|
|
|
|
roles: {
|
|
|
|
|
select: {
|
|
|
|
|
role: true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
2023-07-18 21:23:45 +00:00
|
|
|
if (user) {
|
|
|
|
|
await prisma.collection.upsert({
|
|
|
|
|
where: {
|
|
|
|
|
user_id: user.id
|
|
|
|
|
},
|
|
|
|
|
create: {
|
|
|
|
|
user_id: user.id
|
|
|
|
|
},
|
|
|
|
|
update: {
|
|
|
|
|
user_id: user.id
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
await prisma.wishlist.upsert({
|
|
|
|
|
where: {
|
|
|
|
|
user_id: user.id
|
|
|
|
|
},
|
|
|
|
|
create: {
|
|
|
|
|
user_id: user.id,
|
|
|
|
|
name: 'My Wishlist'
|
|
|
|
|
},
|
|
|
|
|
update: {
|
|
|
|
|
user_id: user.id,
|
|
|
|
|
name: 'My Wishlist'
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
2023-05-21 05:18:04 +00:00
|
|
|
} catch (e) {
|
|
|
|
|
// TODO: need to return error message to the client
|
|
|
|
|
console.error(e);
|
2023-05-29 06:34:39 +00:00
|
|
|
form.data.password = '';
|
2023-07-01 23:12:17 +00:00
|
|
|
return setError(form, '', 'Your username or password is incorrect.');
|
2023-05-21 05:18:04 +00:00
|
|
|
}
|
2023-05-29 06:34:39 +00:00
|
|
|
form.data.username = '';
|
|
|
|
|
form.data.password = '';
|
2023-05-21 05:18:04 +00:00
|
|
|
return { form };
|
|
|
|
|
}
|
|
|
|
|
};
|