[英]How to compare password before change in NodeJS?
当用户尝试更改密码时,我无法比较旧密码和新密码。 我创建了一个 controller 可以帮助用户执行此操作,但我无法运行或调用 API。 所以,我需要帮助,任何人都可以帮助我做到这一点,一些建议或任何建议都会很好。
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);
}
};
请帮我在更改之前比较密码。 谢谢您的帮助
您可以这样做首先检查旧密码然后更新它
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.