54 lines
1.1 KiB
TypeScript
54 lines
1.1 KiB
TypeScript
|
'use server';
|
||
|
|
||
|
import { cookies } from 'next/headers';
|
||
|
import { redirect } from 'next/navigation';
|
||
|
import { Argon2id } from 'oslo/password';
|
||
|
import { lucia } from 'app/lib/lucia';
|
||
|
import prisma from 'app/lib/db';
|
||
|
|
||
|
export type User = {
|
||
|
id?: number,
|
||
|
email: string,
|
||
|
password: string,
|
||
|
}
|
||
|
|
||
|
const signIn = async (clientUser: User) => {
|
||
|
|
||
|
try {
|
||
|
const user = await prisma.user.findFirst({
|
||
|
where: { email: clientUser.email },
|
||
|
});
|
||
|
|
||
|
if (!user) {
|
||
|
// https://www.robinwieruch.de/next-forms/
|
||
|
throw new Error('Incorrect email or password');
|
||
|
}
|
||
|
|
||
|
const validPassword = await new Argon2id().verify(
|
||
|
user.password,
|
||
|
clientUser.password
|
||
|
);
|
||
|
|
||
|
if (!validPassword) {
|
||
|
// https://www.robinwieruch.de/next-forms/
|
||
|
throw new Error('Incorrect email or password');
|
||
|
}
|
||
|
|
||
|
const session = await lucia.createSession(user.id.toString(), {});
|
||
|
const sessionCookie = lucia.createSessionCookie(session.id);
|
||
|
|
||
|
cookies().set(
|
||
|
sessionCookie.name,
|
||
|
sessionCookie.value,
|
||
|
sessionCookie.attributes
|
||
|
);
|
||
|
} catch (error) {
|
||
|
// TODO: add error feedback yourself
|
||
|
// https://www.robinwieruch.de/next-forms/
|
||
|
}
|
||
|
|
||
|
redirect('/dashboard');
|
||
|
};
|
||
|
|
||
|
export { signIn };
|