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

95 lines
2.2 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";
2023-05-22 07:20:48 -05:00
import fs from "fs";
import path from "path";
import bcrypt from "bcrypt";
2023-05-20 14:25:00 -05:00
export default async function updateUser(
user: AccountSettings,
userId: number
) {
// Password Settings
if (user.newPassword && user.oldPassword) {
const targetUser = await prisma.user.findUnique({
where: {
id: user.id,
},
});
if (
targetUser &&
bcrypt.compareSync(user.oldPassword, targetUser.password)
) {
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(user.newPassword, saltRounds);
await prisma.user.update({
where: {
id: userId,
},
data: {
password: newHashedPassword,
},
});
} else {
return { response: "Old password is incorrect.", 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 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.");
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 == "") {
2023-05-22 07:20:48 -05:00
fs.unlink(`data/uploads/avatar/${userId}.jpg`, (err) => {
if (err) console.log(err);
});
}
2023-05-20 14:25:00 -05:00
// Other settings
2023-05-20 14:25:00 -05:00
const updatedUser = await prisma.user.update({
where: {
id: userId,
},
data: {
name: user.name,
email: user.email,
isPrivate: user.isPrivate,
2023-05-20 14:25:00 -05:00
whitelistedUsers: user.whitelistedUsers,
},
});
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
}