简体   繁体   中英

cannot compare password with bcrypt compare

Im trying to build a node api for change password,

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

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,

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

feel free to use console.log('') when you have doubts about anything it will give you a good vision about your code status

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');

                            });
                        });

                    };
                };
            });
        }

    })
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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