无法使用 bcrypt compare 比较密码

cannot compare password with bcrypt compare

我正在尝试构建一个节点 api 以更改密码,

用户必须输入当前密码和新密码

当 bcrypt.compare 新的 currentPassword 存储在数据库上时,我得到的总是错误的,无论它是错的还是正确的

const changePass = async (req, res, next) => {


//email and password
const CurrentPassword = req.body.currPassword
let password1 = ''+req.body.password1
let password2 = ''+req.body.password2

const hashedPassword = await bcrypt.hash(password1, 10); 

let id = "" + req.body.id

User.findById( id )
    .then(user => {
        bcrypt.compare(CurrentPassword, user.password, (err, data) => {

            if (err) throw err

            if (data) {

                User.findByIdAndUpdate(id, {password : hashedPassword    }, {new: false}, (err) => {
                if (err) throw err
            })

            } else {
                return res.status(401).json({ msg: "Invalid" })
            }

        })

    })

}

如果你想学习bcrypt我推荐你访问bcrypt NPM因为它会为你以后节省太多时间,

在你的情况下,我对你的代码做了一些修改,以检查当前密码 OLD,然后比较 newPassword1 和确认 passwordConfirmation

当您对任何事情有疑问时,请随意使用 console.log('') 它会让您对代码状态有一个很好的了解

const changePassword = async (req, res, next) => {
let id = req.body.nid;
if(id){
    console.log('Im here')
    const old = req.body.old;
    const newP = req.body.newP;
    const newP2 = req.body.newP2;

    User.findById(id,(err,user)=>{
        if(user){
            console.log(user)
            const hash = user.password;
            bcrypt.compare(old,hash,function (err,res){
                if(res){
                    if(newP === newP2){
                        bcrypt.hash(newP,10, (err,hash)=>{
                            user.password = hash;
                            user.save( (err,user) =>{
                                if(err) return console.error(err);
                                console.log(user.userName +' your password has been changed');

                            });
                        });

                    };
                };
            });
        }

    })
  }
}