i have a problem to compare old and new password when user try to change their password. I created a controller that can help user to do that but i can not run or call the API. so, i need help that anybody can help me to do this, some suggestions or any advices would be nice.
exports.changePassword = (req, res) => {
try {
const user = User.findByPk(req.params.user_id);
var body = req.body;
if (!user) {
return res.status(400).send("invalid value");
}
const salt = bcrypt.genSaltSync(10);
const newPassword = bcrypt.hashSync(body.newPassword, salt);
bcrypt.compare(body.password, newPassword, salt, function (err, isMatch) {
if (err) {
throw err;
} else if (!isMatch) {
console.log("Password doesn't match!");
} else {
console.log("Password matches!");
}
});
user.password = body.password;
user.update(
{
password: newPassword,
updated_at: now(),
},
{
where: {
user_id: user.user_id,
},
}
);
} catch (error) {
res.send("An error occured");
console.log(error);
}
};
Please help me to compare password before change. thank you for your help
CodePudding user response:
You can do like this to check old password first and then update it
exports.changePassword = async (req, res) => {
try {
const user = await User.findByPk(req.params.user_id)
var body = req.body
if (!user) {
return res.status(400).send('invalid value')
}
bcrypt.compare(body.password, user.password, async function (err, isMatch) {
if (err) {
throw err
}
if (!isMatch) throw new Error('Password not matched!')
// if not error and password matched then we will hash password
const salt = bcrypt.genSaltSync(10)
const newPassword = bcrypt.hashSync(body.newPassword, salt)
user.set({ password: newPassword, updated_at: now() })
await user.save()
})
res.status(200).send('Password Changed successfully!')
} catch (error) {
res.send('An error occured')
console.log(error)
}
}