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

92 lines
2.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";
const emailEnabled =
2023-07-12 13:26:34 -05:00
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
2023-02-06 11:59:23 -06:00
interface Data {
response: string | object;
2023-02-06 11:59:23 -06:00
}
interface User {
name: string;
2023-07-08 05:35:43 -05:00
username: string;
2023-07-12 13:26:34 -05:00
email?: string;
2023-02-06 11:59:23 -06:00
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;
const checkHasEmptyFields = emailEnabled
2023-07-12 13:26:34 -05:00
? !body.username || !body.password || !body.name || !body.email
: !body.username || !body.password || !body.name;
if (checkHasEmptyFields)
return res
.status(400)
.json({ response: "Please fill out all the fields." });
2023-07-12 13:26:34 -05:00
const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);
// Remove user's who aren't verified for more than 10 minutes
if (emailEnabled)
2023-07-12 14:14:43 -05:00
await prisma.user.deleteMany({
where: {
2023-07-12 14:17:19 -05:00
OR: [
{
email: body.email,
},
{
username: body.username,
},
],
2023-07-12 14:14:43 -05:00
createdAt: {
lt: tenMinutesAgo,
},
emailVerified: null,
2023-07-12 13:26:34 -05:00
},
2023-07-12 14:14:43 -05:00
});
2023-02-06 11:59:23 -06:00
2023-07-12 13:26:34 -05:00
const checkIfUserExists = await prisma.user.findFirst({
where: emailEnabled
2023-07-12 13:26:34 -05:00
? {
OR: [
{
username: body.username.toLowerCase(),
},
2023-07-12 13:26:34 -05:00
{
email: body.email?.toLowerCase(),
},
],
emailVerified: { not: null },
}
: {
username: body.username.toLowerCase(),
},
});
2023-02-06 11:59:23 -06:00
if (!checkIfUserExists) {
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
await prisma.user.create({
data: {
name: body.name,
2023-07-08 05:35:43 -05:00
username: body.username.toLowerCase(),
2023-07-12 13:26:34 -05:00
email: body.email?.toLowerCase(),
2023-02-06 11:59:23 -06:00
password: hashedPassword,
},
});
res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) {
2023-07-12 13:26:34 -05:00
res.status(400).json({ response: "Username and/or Email already exists." });
2023-02-06 11:59:23 -06:00
}
}