daphnis/auth/components/signup/action.ts

101 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-06-29 05:22:22 +00:00
"use server";
import { generateId } from "lucia";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { Argon2id } from "oslo/password";
import { lucia } from "@/lib/lucia";
2024-06-29 06:37:50 +00:00
import { daphnis, artemis } from "@/lib/prisma";
2024-06-29 05:22:22 +00:00
const signUp = async (formData: FormData) => {
const formDataRaw = {
username: formData.get("username") as string,
email: formData.get("email") as string,
accessCode: formData.get("accessCode") as string,
password: formData.get("password") as string,
confirmPassword: formData.get("confirmPassword") as string,
};
if (formDataRaw.password !== formDataRaw.confirmPassword) {
return { error: "Passwords do not match" };
}
try {
2024-06-29 06:37:50 +00:00
// Check if access code is already used in daphnis database
const existingUser = await daphnis.user.findFirst({
2024-06-29 05:22:22 +00:00
where: {
accessCode: formDataRaw.accessCode,
},
});
if (existingUser) {
return { error: "Access Code already in use" };
}
2024-06-29 06:37:50 +00:00
// Check if username is already used in daphnis database
const existingUsername = await daphnis.user.findFirst({
2024-06-29 05:22:22 +00:00
where: {
username: formDataRaw.username,
},
});
if (existingUsername) {
return { error: "Username is currently taken" };
}
2024-06-29 06:37:50 +00:00
const existingEmail = await daphnis.user.findFirst({
2024-06-29 05:22:22 +00:00
where: {
email: formDataRaw.email,
},
});
if (existingEmail) {
return { error: "Email is already in use" };
}
// Check if access code exists in artemis database
const existingAccessCode = await artemis.aime_card.findFirst({
where: {
access_code: formDataRaw.accessCode,
},
});
if (!existingAccessCode) {
return { error: "Not in artemis's database, Nice try ^_^" };
}
const hashedPassword = await new Argon2id().hash(formDataRaw.password);
const userId = generateId(15);
2024-06-29 06:37:50 +00:00
// Create user in the daphnis database
await daphnis.user.create({
2024-06-29 05:22:22 +00:00
data: {
id: userId,
username: formDataRaw.username,
email: formDataRaw.email,
accessCode: formDataRaw.accessCode,
hashedPassword,
},
});
// Create session and set cookie
const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
console.log("Account created");
// Redirect to home page
} catch (error: any) {
return { error: "Account creation failed: " + error.message };
}
2024-06-29 05:46:07 +00:00
redirect("/home");
2024-06-29 05:22:22 +00:00
};
export { signUp };