【问题标题】:How do we hash a put request password?我们如何对 put 请求密码进行哈希处理?
【发布时间】:2021-04-02 12:05:07
【问题描述】:

大家好,我想在我的 express-mongoose 服务器中使用 bcrypt 对我的 put 请求进行哈希处理

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)
})

除了散列更新的密码之外,更新请求中的所有其他功能都可以正常工作。作为新手,我需要您的帮助/最佳方法建议。 提前谢谢...

【问题讨论】:

  • 您是否尝试对纯文本密码进行哈希处理并在数据库中进行更新?如果是,您需要在 findByIdAndUpdate 之前对其进行哈希处理

标签: express mongoose put bcrypt


【解决方案1】:

解决方案 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多