el.xwx.moe/lib/api/controllers/users/postUser.ts

149 lines
4.4 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";
import isServerAdmin from "../../isServerAdmin";
2023-02-06 11:59:23 -06:00
const emailEnabled =
2023-07-12 13:26:34 -05:00
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
2024-05-03 09:22:45 -05:00
const stripeEnabled = process.env.STRIPE_SECRET_KEY ? true : false;
2023-07-12 13:26:34 -05:00
2023-02-06 11:59:23 -06:00
interface Data {
response: string | object;
status: number;
2023-02-06 11:59:23 -06:00
}
interface User {
name: string;
2023-07-19 15:39:59 -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 postUser(
2023-02-06 11:59:23 -06:00
req: NextApiRequest,
res: NextApiResponse
): Promise<Data> {
let isAdmin = await isServerAdmin({ req });
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" && !isAdmin) {
return { response: "Registration is disabled.", status: 400 };
}
2023-02-06 11:59:23 -06:00
const body: User = req.body;
const checkHasEmptyFields = emailEnabled
2023-07-19 15:39:59 -05:00
? !body.password || !body.name || !body.email
2023-07-12 13:26:34 -05:00
: !body.username || !body.password || !body.name;
2023-11-19 21:32:23 -06:00
if (!body.password || body.password.length < 8)
return { response: "Password must be at least 8 characters.", status: 400 };
2023-11-19 21:28:02 -06:00
2023-07-12 13:26:34 -05:00
if (checkHasEmptyFields)
return { response: "Please fill out all the fields.", status: 400 };
// Check email (if enabled)
const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(body.email?.toLowerCase() || ""))
return { response: "Please enter a valid email.", status: 400 };
2023-07-19 00:23:53 -05:00
// Check username (if email was disabled)
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
2024-08-14 16:26:38 -05:00
const autoGeneratedUsername = "user" + Math.round(Math.random() * 1000000000);
if (body.username && !checkUsername.test(body.username?.toLowerCase()))
return {
2023-07-19 00:23:53 -05:00
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
status: 400,
};
2024-08-14 16:26:38 -05:00
else if (!body.username) {
body.username = autoGeneratedUsername;
}
2023-07-19 00:23:53 -05:00
2023-07-12 13:26:34 -05:00
const checkIfUserExists = await prisma.user.findFirst({
2024-05-03 09:22:45 -05:00
where: {
OR: [
{
email: body.email ? body.email.toLowerCase().trim() : undefined,
2024-05-03 09:22:45 -05:00
},
{
username: body.username
? body.username.toLowerCase().trim()
: undefined,
2023-07-12 13:26:34 -05:00
},
2024-05-03 09:22:45 -05:00
],
},
2023-07-12 13:26:34 -05:00
});
2023-02-06 11:59:23 -06:00
if (!checkIfUserExists) {
2024-05-12 23:27:29 -05:00
const autoGeneratedUsername =
"user" + Math.round(Math.random() * 1000000000);
2023-02-06 11:59:23 -06:00
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
2024-05-03 09:22:45 -05:00
// Subscription dates
const currentPeriodStart = new Date();
const currentPeriodEnd = new Date();
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
if (isAdmin) {
2024-05-03 09:22:45 -05:00
const user = await prisma.user.create({
data: {
name: body.name,
2024-05-12 23:27:29 -05:00
username: emailEnabled
2024-08-14 16:26:38 -05:00
? (body.username as string).toLowerCase().trim() ||
autoGeneratedUsername
2024-05-12 23:27:29 -05:00
: (body.username as string).toLowerCase().trim(),
2024-05-03 09:22:45 -05:00
email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
password: hashedPassword,
emailVerified: new Date(),
subscriptions: stripeEnabled
? {
create: {
stripeSubscriptionId:
"fake_sub_" + Math.round(Math.random() * 10000000000000),
active: true,
currentPeriodStart,
currentPeriodEnd,
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
},
createdAt: true,
},
});
return { response: user, status: 201 };
2024-05-03 09:22:45 -05:00
} else {
await prisma.user.create({
data: {
name: body.name,
username: emailEnabled
2024-05-12 23:27:29 -05:00
? autoGeneratedUsername
2024-05-03 09:22:45 -05:00
: (body.username as string).toLowerCase().trim(),
email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
password: hashedPassword,
},
});
2023-02-06 11:59:23 -06:00
return { response: "User successfully created.", status: 201 };
2024-05-03 09:22:45 -05:00
}
} else {
return { response: "Email or Username already exists.", status: 400 };
2023-02-06 11:59:23 -06:00
}
}