【问题标题】:Changing user's password (bcrypt) using PUT method (mysql2, sequelize, express)使用 PUT 方法(mysql2、sequelize、express)更改用户密码(bcrypt)
【发布时间】:2021-08-27 13:07:33
【问题描述】:

我正在尝试创建一个用户可以更改其详细信息的功能。除非我尝试允许用户更改密码,否则其他项目都有效。

编辑:如果我也更改密码,代码可以工作,否则会导致服务器崩溃并给出 bcrypt 错误。如果我不想更改密码,有什么办法吗?还是我必须将它们分开?

这是我得到的错误:

Error: data and salt arguments required

路线

router.put('/:user_id/edit', validateToken, async (req, res) => {
    const userId = req.params.user_id;
    const { email, 
            password, 
            first_name, 
            last_name,
            role_id } = req.body;

        await bcrypt.hash(password, 10).then((hash) => {
            Users.update({
                email: email,
                password: hash,
                first_name: first_name,
                last_name: last_name,
                role_id: role_id
            }, { where: {user_id: userId} });
            res.json('User updated successfully');
        })
})

【问题讨论】:

  • 你确定“密码”不是未定义的吗?
  • @griFlo 大声笑,你是对的。我没有输入密码更改。我的问题实际上是如果用户不想更改密码,我该如何使这段代码工作。 (更新了我的帖子)

标签: node.js express sequelize.js put bcrypt


【解决方案1】:

我刚刚为它做了一个 if 语句,哈哈。对不起各位。

router.put('/:user_id/edit', validateToken, (req, res) => {
    const userId = req.params.user_id;
    const { email, 
            password, 
            first_name, 
            last_name,
            role_id } = req.body;

        if (password != undefined) {
            bcrypt.hash(password, 10).then((hash) => {
                Users.update({
                    email: email,
                    password: hash,
                    first_name: first_name,
                    last_name: last_name,
                    role_id: role_id
                }, { where: {user_id: userId} });
                res.json('User updated successfully');
            })
        } else {
            Users.update({
                email: email,
                first_name: first_name,
                last_name: last_name,
                role_id: role_id
            }, { where: {user_id: userId} });
            res.json('User updated successfully');
        }
});

【讨论】:

    【解决方案2】:

    因此,据我了解,您想要创建一个编辑配置文件功能,但问题是当您不更改密码时它会崩溃。解决方法很简单。

    解决方案

    您可以通过验证输入来处理这个问题,这是您需要小心的事情。最简单的方法是使用 if 语句,如下所示:
    if (email == '' || password == '' || ... || role_id == '') { // Check if all the parameters are given
       return false; // Will terminate the callback function
    }
    

    虽然这可能有点矫枉过正,但您希望以更好的方式处理它,例如忽略更改密码的部分 os ots empty,如下所示:

    if (password != '') {
      // Change the password here
    }
    

    另一种解决方案是将密码更改功能移动到另一个端点(或修改端点,以便在满足条件时更改密码)并分别处理密码和一般配置文件信息,这感觉是一种更好的方法,但我不确定。

    【讨论】:

      猜你喜欢
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2021-10-20
      相关资源
      最近更新 更多