简体   繁体   English

无法将密码与 bcrypt compare 进行比较

[英]cannot compare password with bcrypt compare

Im trying to build a node api for change password,我正在尝试构建一个节点 api 以更改密码,

User must type the currentPassword and the new password用户必须输入当前密码和新密码

when bcrypt.compare the new currentPassword with the stored on db, i got always false, whatever it's wrong or correct当 bcrypt.compare 新的 currentPassword 与存储在 db 上的密码时,我总是错误的,无论它是错误的还是正确的

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

        })

    })

}

If you want to learn bcrypt I recommend you to visit bcrypt NPM because it will save you too much time later,如果你想学习 bcrypt 我建议你访问bcrypt NPM因为它会为你节省太多的时间,

in your case I made some modification on your code in order to check for the current password OLD and then compare between the newPassword1 and the confirmation passwordConfirmation在您的情况下,我对您的代码进行了一些修改,以检查当前密码OLD ,然后在newPassword1和确认passwordConfirmation Confirmation 之间进行比较

feel free to use console.log('') when you have doubts about anything it will give you a good vision about your code status当您对任何事情有疑问时,请随意使用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');

                            });
                        });

                    };
                };
            });
        }

    })
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM