问题描述
大家好,我正在尝试在我的 express-mongoose 服务器中使用 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 的中间件 here。