嗨,大家都在我的快递猫鼬服务器中尝试使用bcrypt散列我的put请求
看跌请求
// updating a user
router.put('/:id', async (req, res) => {
const {error} = validate(req.body)
if (error) return res.status(400).send(error.details[0].message)
const user = await User.findByIdAndUpdate(req.params.id, {
$set : {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
})
// hashing user passwords
const salt = await bcrypt.genSalt(10)
user.password = await bcrypt.hash(user.password, salt)
if (!user) return res.status(404).send('User with that id does not exist')
res.send(user)
})
除了散列更新后的密码外,更新请求中的所有其他功能都能完美工作。作为一名新手,我需要你在这方面的帮助/最佳方法建议。提前感谢。。。
解决方案1:简单方法
对于您的个人解决方案,在不真正修改代码的情况下,它的工作方式如下。
// updating a user
router.put('/:id', async (req, res) => {
const {error} = validate(req.body)
if (error) return res.status(400).send(error.details[0].message)
// Why not make the hash function here?
const salt = await bcrypt.genSalt(10)
const newPassword = await bcrypt.hash(req.body.password, salt)
const user = await User.findByIdAndUpdate(req.params.id, {
$set : {
name: req.body.name,
email: req.body.email,
password: newPassword
}
})
if (!user) return res.status(404).send('User with that id does not exist')
res.send(user)
})
您的user.password
呼叫有一个错误。findByIdAndUpdate
方法不会返回可以立即修改的对象。在上面的解决方法中,我们只需移动函数,使其在更新文档之前先散列新密码。
解决方案2:我自己的风格
对于我个人的解决方案,我会这样做。假设您有一个userModel
,它存储了User
实体的模式。我将添加一个新的中间件,它将在每次密码更改时运行。
/** your user schema code. **/
userSchema.pre('save', async function (next) {
// Only run the encryption if password is modified.
if (!this.isModified('password')) {
return next();
}
// Hash the password with BCRYPT Algorithm, with 12 characters of randomly generated salt.
this.password = await bcrypt.hash(this.password, 12);
next();
});
接下来,我们将创建一个新的专用路由来处理密码更改。我认为最好我们为它定义一个新的路由,因为密码是敏感数据。下面是伪代码,不要立即复制粘贴,它不会工作。
const user = await User.findById(...);
user.password = req.body.password;
await user.save({ validateBeforeSave: true });
请记住,每次运行save
命令后,都会运行save
中间件。
点击此处进一步阅读Mongoose的中间件。