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

182 lines
4.8 KiB
TypeScript
Raw Normal View History

2023-05-20 14:25:00 -05:00
import { prisma } from "@/lib/api/db";
import { AccountSettings } from "@/types/global";
import bcrypt from "bcrypt";
import removeFile from "@/lib/api/storage/removeFile";
import createFile from "@/lib/api/storage/createFile";
2023-08-03 16:54:04 -05:00
import updateCustomerEmail from "@/lib/api/updateCustomerEmail";
import createFolder from "@/lib/api/storage/createFolder";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
2023-05-20 14:25:00 -05:00
export default async function updateUser(
user: AccountSettings,
sessionUser: {
id: number;
username: string;
email: string;
isSubscriber: boolean;
}
) {
2023-08-03 16:54:04 -05:00
if (emailEnabled && !user.email)
2023-07-12 13:26:34 -05:00
return {
2023-08-03 16:54:04 -05:00
response: "Email invalid.",
status: 400,
};
else if (!user.username)
return {
response: "Username invalid.",
2023-07-12 13:26:34 -05:00
status: 400,
};
2023-07-19 00:23:53 -05:00
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
2023-07-19 17:38:36 -05:00
if (!checkUsername.test(user.username.toLowerCase()))
2023-07-19 00:23:53 -05:00
return {
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
status: 400,
};
2023-07-18 11:44:37 -05:00
const userIsTaken = await prisma.user.findFirst({
where: {
id: { not: sessionUser.id },
2023-08-03 16:54:04 -05:00
OR: emailEnabled
? [
{
username: user.username.toLowerCase(),
},
{
email: user.email?.toLowerCase(),
},
]
2023-08-04 19:32:13 -05:00
: [
{
username: user.username.toLowerCase(),
},
],
2023-07-18 11:44:37 -05:00
},
});
if (userIsTaken)
return {
response: "Username/Email is taken.",
status: 400,
};
// Avatar Settings
2023-05-22 07:20:48 -05:00
const profilePic = user.profilePic;
2023-06-08 08:39:22 -05:00
if (profilePic.startsWith("data:image/jpeg;base64")) {
if (user.profilePic.length < 1572864) {
2023-05-22 07:20:48 -05:00
try {
const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, "");
2023-08-03 16:54:04 -05:00
createFolder({ filePath: `uploads/avatar` });
await createFile({
filePath: `uploads/avatar/${sessionUser.id}.jpg`,
data: base64Data,
isBase64: true,
2023-05-22 07:20:48 -05:00
});
} catch (err) {
console.log("Error saving image:", err);
}
} else {
console.log("A file larger than 1.5MB was uploaded.");
return {
response: "A file larger than 1.5MB was uploaded.",
status: 400,
};
2023-05-22 07:20:48 -05:00
}
2023-06-08 08:39:22 -05:00
} else if (profilePic == "") {
removeFile({ filePath: `uploads/avatar/${sessionUser.id}.jpg` });
2023-05-22 07:20:48 -05:00
}
2023-05-20 14:25:00 -05:00
// Other settings
2023-07-12 13:26:34 -05:00
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(user.newPassword || "", saltRounds);
2023-05-20 14:25:00 -05:00
const updatedUser = await prisma.user.update({
where: {
id: sessionUser.id,
2023-05-20 14:25:00 -05:00
},
data: {
name: user.name,
2023-07-08 05:35:43 -05:00
username: user.username.toLowerCase(),
2023-07-12 13:26:34 -05:00
email: user.email?.toLowerCase(),
isPrivate: user.isPrivate,
archiveAsScreenshot: user.archiveAsScreenshot,
archiveAsPDF: user.archiveAsPDF,
archiveAsWaybackMachine: user.archiveAsWaybackMachine,
2023-07-12 13:26:34 -05:00
password:
user.newPassword && user.newPassword !== ""
? newHashedPassword
: undefined,
2023-05-20 14:25:00 -05:00
},
include: {
2023-08-04 19:32:13 -05:00
whitelistedUsers: true,
},
2023-05-20 14:25:00 -05:00
});
const { whitelistedUsers, password, ...userInfo } = updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = user.whitelistedUsers || [];
// Get the current whitelisted usernames
2023-08-04 19:32:13 -05:00
const currentWhitelistedUsernames: string[] = whitelistedUsers.map(
(user) => user.username
);
// Find the usernames to be deleted (present in current but not in new)
const usernamesToDelete: string[] = currentWhitelistedUsernames.filter(
2023-08-04 19:32:13 -05:00
(username) => !newWhitelistedUsernames.includes(username)
);
// Find the usernames to be created (present in new but not in current)
const usernamesToCreate: string[] = newWhitelistedUsernames.filter(
2023-08-04 19:32:13 -05:00
(username) =>
!currentWhitelistedUsernames.includes(username) && username.trim() !== ""
);
// Delete whitelistedUsers that are not present in the new list
await prisma.whitelistedUser.deleteMany({
where: {
userId: sessionUser.id,
username: {
in: usernamesToDelete,
},
},
});
// Create new whitelistedUsers that are not in the current list, no create many ;(
for (const username of usernamesToCreate) {
await prisma.whitelistedUser.create({
data: {
username,
userId: sessionUser.id,
},
});
}
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
2023-08-21 15:11:13 -05:00
if (STRIPE_SECRET_KEY && emailEnabled)
await updateCustomerEmail(
STRIPE_SECRET_KEY,
sessionUser.email,
2023-08-03 16:54:04 -05:00
user.email as string
);
2023-06-08 08:39:22 -05:00
const response: Omit<AccountSettings, "password"> = {
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
2023-06-08 08:39:22 -05:00
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
};
return { response, status: 200 };
2023-05-20 14:25:00 -05:00
}