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

93 lines
2.4 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";
import updateCustomerEmail from "../../updateCustomerEmail";
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-07-12 13:26:34 -05:00
if (!user.username || !user.email)
return {
response: "Username/Email invalid.",
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,/, "");
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,
2023-05-20 14:25:00 -05:00
whitelistedUsers: user.whitelistedUsers,
2023-07-12 13:26:34 -05:00
password:
user.newPassword && user.newPassword !== ""
? newHashedPassword
: undefined,
2023-05-20 14:25:00 -05:00
},
});
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const PRICE_ID = process.env.PRICE_ID;
if (STRIPE_SECRET_KEY && PRICE_ID)
await updateCustomerEmail(
STRIPE_SECRET_KEY,
PRICE_ID,
sessionUser.email,
user.email
);
2023-05-27 14:05:07 -05:00
const { password, ...userInfo } = updatedUser;
2023-05-22 07:20:48 -05:00
2023-06-08 08:39:22 -05:00
const response: Omit<AccountSettings, "password"> = {
...userInfo,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
};
return { response, status: 200 };
2023-05-20 14:25:00 -05:00
}