node Bcrypt compare always returns success

Viewed 1069

always when I try to compare between the newUser.password with profile.password it gives me success even if I put a wrong password

and here is my code

    const bcrypt = require('bcrypt')

const router = require('express').Router()
// const jwt = require('jsonwebtoken')
let User = require('../models/user.model')

 router.route('/login').post(async(req, res) => {
    var newUser = {};
    newUser.email = req.body.email;

    newUser.password = req.body.password;
    console.log(newUser.password)
     User.findOne({ email: newUser.email })
      .then(profile => {
        if (!profile) {
          res.send("User not exist");

here it will compare for me the hashed pass with the pass that the client give

        }else if(bcrypt.compare(newUser.password, profile.password)){
            res.send("success");

here will stop

        }
        else if((newUser.password !== profile.password)){
          res.send("wrong");
          }
      })
      .catch(err => res.status(400).json('Erorr: ' + err))
        
})

router.route('/add').post(async(req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10)

    const username = req.body.username
    const email = req.body.email
    const password = hashedPassword
    const firstname = req.body.firstname
    const lastname = req.body.lastname

    const newUser = new User({username, email, password, firstname, lastname})
    
    // const accessToken = jwt.sign(password, process.env.ACCESS_TOKEN_SECRET)
    // res.json({ accessToken: accessToken })

    newUser.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Erorr: ' + err))
})

// function authToken(req, res, next){
//     const authHeader = req.headers['authorization']
//     const token = authHeader && authHeader.split(' ')[1]
//     if (token == null ) return res.sendStatus(401)

//     jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, password) => {
//         if (err) return res.sendStatus(403)
//         req.password = password
//         next()
//     })
// }

module.exports = router
2 Answers

bcrypt.compare is asynchronous so use async and await keyword. Try this,

newUser.password = req.body.password;
console.log(newUser.password)
 User.findOne({ email: newUser.email })
  //async keyword below
  .then(async profile => {
    if (!profile) {
      res.send("User not exist");

  //await keyword below
}else if(await bcrypt.compare(newUser.password, profile.password)){
        res.send("success");

Probably you are using async of compare and hash You should chain with then or async await Here is short form of your code and run mongodb and node user.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

let UserSchema = new mongoose.Schema({
    email: String,
    password: String,
});

run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const UserModel = mongoose.model('user', UserSchema);
    const newUser = { email: 'test@test.com', password: 'Alexa123' };
    const hasPassword = bcrypt.hashSync(newUser.password, 10);
    const user = new UserModel({ email: newUser.email, password: hasPassword });
    await user.save();

    const getUser = await UserModel.findOne({ email: 'test@test.com' }).exec();
    console.log(getUser);
    // put password wrong here you will get result as expected
    if (bcrypt.compareSync('Alexa123', getUser.password)) {
        console.log('password matched');
    } else {
        console.log('password is wrong');
    }
}

Related