@@ -1,9 +1,7 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import bcrypt from "bcrypt";
|
||||
import { PostUserSchema } from "@/lib/shared/schemaValidation";
|
||||
import isAuthenticatedRequest from "../../isAuthenticatedRequest";
|
||||
import { Subscription, User } from "@prisma/client";
|
||||
import isServerAdmin from "../../isServerAdmin";
|
||||
|
||||
const emailEnabled =
|
||||
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
|
||||
@@ -14,61 +12,66 @@ interface Data {
|
||||
status: number;
|
||||
}
|
||||
|
||||
interface User {
|
||||
name: string;
|
||||
username?: string;
|
||||
email?: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export default async function postUser(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
): Promise<Data> {
|
||||
const parentUser = await isAuthenticatedRequest({ req });
|
||||
const isAdmin =
|
||||
parentUser && parentUser.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
|
||||
|
||||
const DISABLE_INVITES = process.env.DISABLE_INVITES === "true";
|
||||
let isAdmin = await isServerAdmin({ req });
|
||||
|
||||
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" && !isAdmin) {
|
||||
return { response: "Registration is disabled.", status: 400 };
|
||||
}
|
||||
|
||||
const dataValidation = PostUserSchema().safeParse(req.body);
|
||||
const body: User = req.body;
|
||||
|
||||
if (!dataValidation.success) {
|
||||
return {
|
||||
response: `Error: ${
|
||||
dataValidation.error.issues[0].message
|
||||
} [${dataValidation.error.issues[0].path.join(", ")}]`,
|
||||
status: 400,
|
||||
};
|
||||
}
|
||||
const checkHasEmptyFields = emailEnabled
|
||||
? !body.password || !body.name || !body.email
|
||||
: !body.username || !body.password || !body.name;
|
||||
|
||||
const { name, email, password, invite } = dataValidation.data;
|
||||
let { username } = dataValidation.data;
|
||||
if (!body.password || body.password.length < 8)
|
||||
return { response: "Password must be at least 8 characters.", status: 400 };
|
||||
|
||||
if (invite && (DISABLE_INVITES || !emailEnabled)) {
|
||||
return { response: "You are not authorized to invite users.", status: 401 };
|
||||
} else if (invite && !parentUser) {
|
||||
return { response: "You must be logged in to invite users.", status: 401 };
|
||||
}
|
||||
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 };
|
||||
|
||||
// Check username (if email was disabled)
|
||||
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
|
||||
|
||||
const autoGeneratedUsername = "user" + Math.round(Math.random() * 1000000000);
|
||||
|
||||
if (!username) {
|
||||
username = autoGeneratedUsername;
|
||||
}
|
||||
|
||||
if (!emailEnabled && !password) {
|
||||
if (body.username && !checkUsername.test(body.username?.toLowerCase()))
|
||||
return {
|
||||
response: "Password is required.",
|
||||
response:
|
||||
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
|
||||
status: 400,
|
||||
};
|
||||
else if (!body.username) {
|
||||
body.username = autoGeneratedUsername;
|
||||
}
|
||||
|
||||
const checkIfUserExists = await prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
email: email ? email.toLowerCase().trim() : undefined,
|
||||
email: body.email ? body.email.toLowerCase().trim() : undefined,
|
||||
},
|
||||
{
|
||||
username: username ? username.toLowerCase().trim() : undefined,
|
||||
username: body.username
|
||||
? body.username.toLowerCase().trim()
|
||||
: undefined,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -80,57 +83,65 @@ export default async function postUser(
|
||||
|
||||
const saltRounds = 10;
|
||||
|
||||
const hashedPassword = bcrypt.hashSync(password || "", saltRounds);
|
||||
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: name,
|
||||
username: emailEnabled ? username || autoGeneratedUsername : username,
|
||||
email: emailEnabled ? email : undefined,
|
||||
emailVerified: isAdmin ? new Date() : undefined,
|
||||
password: password ? hashedPassword : undefined,
|
||||
parentSubscription:
|
||||
parentUser && invite
|
||||
? {
|
||||
connect: {
|
||||
id: (parentUser.subscriptions as Subscription).id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
subscriptions:
|
||||
stripeEnabled && isAdmin
|
||||
// Subscription dates
|
||||
const currentPeriodStart = new Date();
|
||||
const currentPeriodEnd = new Date();
|
||||
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
|
||||
|
||||
if (isAdmin) {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
username: emailEnabled
|
||||
? (body.username as string).toLowerCase().trim() ||
|
||||
autoGeneratedUsername
|
||||
: (body.username as string).toLowerCase().trim(),
|
||||
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: new Date(),
|
||||
currentPeriodEnd: new Date(
|
||||
new Date().setFullYear(new Date().getFullYear() + 1000)
|
||||
), // 1000 years from now
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
select: isAdmin
|
||||
? {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
emailVerified: true,
|
||||
password: true,
|
||||
subscriptions: {
|
||||
select: {
|
||||
active: true,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
emailVerified: true,
|
||||
subscriptions: {
|
||||
select: {
|
||||
active: true,
|
||||
},
|
||||
createdAt: true,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
},
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const { password: pass, ...userWithoutPassword } = user as User;
|
||||
return { response: userWithoutPassword, status: 201 };
|
||||
return { response: user, status: 201 };
|
||||
} else {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
name: body.name,
|
||||
username: emailEnabled
|
||||
? autoGeneratedUsername
|
||||
: (body.username as string).toLowerCase().trim(),
|
||||
email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
|
||||
password: hashedPassword,
|
||||
},
|
||||
});
|
||||
|
||||
return { response: "User successfully created.", status: 201 };
|
||||
}
|
||||
} else {
|
||||
return { response: "Email or Username already exists.", status: 400 };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user