node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
user-change-password.js
(1008B)
1 import bcrypt from "bcryptjs";
2 import User from "../models/user.js";
3
4 const changePassword = async (req, res) => {
5 const { email, oldPassword, newPassword } = req.body;
6
7 try {
8 const existingUser = await User.findOne({ email });
9
10 if (!existingUser) {
11 return res.status(404).json({ message: "User Does Not Exist" });
12 }
13
14 if (!req.userId) {
15 return res.json({ message: "Unauthenticated" });
16 }
17
18 const isPasswordCorrect = await bcrypt.compare(
19 oldPassword,
20 existingUser.password
21 );
22
23 if (!isPasswordCorrect) {
24 return res.status(400).json({ message: "Invalid Password" });
25 }
26
27 const hashedPassword = await bcrypt.hash(newPassword, 12);
28 const updatePassword = await User.findByIdAndUpdate(
29 existingUser._id,
30 { password: hashedPassword },
31 { new: true }
32 );
33
34 res.status(200).json(updatePassword);
35 } catch (error) {
36 res.status(500).json({ message: "Something went wrong" });
37 }
38 };
39
40 export default changePassword;