el.xwx.moe/pages/api/auth/register.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-02-18 21:32:02 -06:00
import { prisma } from "@/lib/api/db";
2023-02-06 11:59:23 -06:00
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
interface Data {
response: string | object;
2023-02-06 11:59:23 -06:00
}
interface User {
name: string;
email: string;
password: string;
}
export default async function Index(
2023-02-06 11:59:23 -06:00
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const body: User = req.body;
if (!body.email || !body.password || !body.name)
return res
.status(400)
.json({ response: "Please fill out all the fields." });
2023-02-06 11:59:23 -06:00
const checkIfUserExists = await prisma.user.findFirst({
where: {
email: body.email,
},
});
if (!checkIfUserExists) {
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
await prisma.user.create({
data: {
name: body.name,
email: body.email,
password: hashedPassword,
},
});
res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) {
res.status(400).json({ response: "User already exists." });
2023-02-06 11:59:23 -06:00
}
}