2023-05-20 14:25:00 -05:00
|
|
|
import { prisma } from "@/lib/api/db";
|
|
|
|
import { AccountSettings } from "@/types/global";
|
2023-05-22 07:20:48 -05:00
|
|
|
import fs from "fs";
|
|
|
|
import path from "path";
|
2023-05-22 15:29:24 -05:00
|
|
|
import bcrypt from "bcrypt";
|
2023-05-20 14:25:00 -05:00
|
|
|
|
|
|
|
export default async function (user: AccountSettings, userId: number) {
|
2023-05-22 07:20:48 -05:00
|
|
|
const profilePic = user.profilePic;
|
|
|
|
|
2023-05-26 14:52:18 -05:00
|
|
|
if (profilePic?.startsWith("data:image/jpeg;base64")) {
|
2023-05-22 07:20:48 -05:00
|
|
|
if ((user?.profilePic?.length as number) < 1572864) {
|
|
|
|
try {
|
|
|
|
const filePath = path.join(
|
|
|
|
process.cwd(),
|
|
|
|
`data/uploads/avatar/${userId}.jpg`
|
|
|
|
);
|
|
|
|
|
|
|
|
const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, "");
|
|
|
|
|
|
|
|
fs.writeFile(filePath, base64Data, "base64", function (err) {
|
|
|
|
console.log(err);
|
|
|
|
});
|
|
|
|
} catch (err) {
|
|
|
|
console.log("Error saving image:", err);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
console.log("A file larger than 1.5MB was uploaded.");
|
|
|
|
}
|
|
|
|
} else if (profilePic === "DELETE") {
|
|
|
|
fs.unlink(`data/uploads/avatar/${userId}.jpg`, (err) => {
|
|
|
|
if (err) console.log(err);
|
|
|
|
});
|
|
|
|
}
|
2023-05-20 14:25:00 -05:00
|
|
|
|
|
|
|
const updatedUser = await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: userId,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
name: user.name,
|
|
|
|
email: user.email,
|
2023-05-22 23:08:16 -05:00
|
|
|
isPrivate: user.isPrivate,
|
2023-05-20 14:25:00 -05:00
|
|
|
whitelistedUsers: user.whitelistedUsers,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2023-05-22 15:29:24 -05:00
|
|
|
if (user.newPassword && user.oldPassword) {
|
|
|
|
const saltRounds = 10;
|
|
|
|
|
|
|
|
const requestOldHashedPassword = bcrypt.hashSync(
|
|
|
|
user.oldPassword,
|
|
|
|
saltRounds
|
|
|
|
);
|
|
|
|
console.log(requestOldHashedPassword);
|
|
|
|
|
|
|
|
if (bcrypt.compareSync(user.oldPassword, updatedUser.password)) {
|
|
|
|
const newHashedPassword = bcrypt.hashSync(user.newPassword, saltRounds);
|
|
|
|
|
|
|
|
await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: userId,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
password: newHashedPassword,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return { response: "Passwords do not match.", status: 403 };
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-27 14:05:07 -05:00
|
|
|
const { password, ...userInfo } = updatedUser;
|
2023-05-22 07:20:48 -05:00
|
|
|
|
2023-05-27 14:05:07 -05:00
|
|
|
return { response: userInfo, status: 200 };
|
2023-05-20 14:25:00 -05:00
|
|
|
}
|