不能用bcrypt比较密码

问题描述 投票:0回答:1

我想建立一个用于修改密码的node api。

用户必须键入当前密码和新密码。

当bcrypt.compare the new currentPassword 与存储在数据库中的密码进行比较时,我得到的结果总是false,不管它是错误的还是正确的。

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

        })

    })

}
javascript node.js mongodb mongoose bcrypt
1个回答
3
投票

如果你想学习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');

                            });
                        });

                    };
                };
            });
        }

    })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.