Bcryptjs always return false

324 Views Asked by At

Hi, I am trying to use the bcriptjs library to compare the encrypted password with the database password.
I am using the "compare" method.

The values ​​that I add to the method are:

  • First, the password that the user gives me. (password)
  • Second, the encrypted password of the database. (pass_db)

    But always return false
const bcrypt = require('bcryptjs')

const create = (req, res) => {
  const { email, password } = req.body;

  if (password.length < 6) {
    res.send({ msgType: "error", msg: "Contraseña almenos 6 caracteres" });
  } else {
    const hash = bcrypt.hashSync(password, 6);

    db.query(
      "INSERT INTO users (email, password) VALUES (?,?)",
      [email, hash],
      (err) => {
        res.send({ msgType: "success", msg: "Usuario creado correctamente" });
      }
    );
  }
};

//TODO Login dont work always return false
const login = (req, res) => {

  //Password from req.body
  const { email, password } = req.body;

  db.query(
    "SELECT password FROM users WHERE email = ?",
    [email],
    (err, result) => {
      // Password encrypted from database
      pass_db = result[0].password;

      if(err){
        res.send({msgType:'error', msg:'Incorrect Login'})
      }

      if(result.length > 0){
        
        //Compare password from req.body with password encryted from database
        const validate = bcrypt.compareSync(password, pass_db);

        //Always false
        console.log(validate);

        if(validate){
          res.send({msgType:'success', msg: "Correct login" })
        }else{
          res.send({msgType:'error', msg: "Incorrect email or password" });
        }
      }else{
        res.send({msgType:'error', msg: "Incorrect email or password" });
      }
    }
  );
};

I tried this code too but didn't work eighter.

bcrypt.hash(password, 6, function (err, hash) {
        if (err) {
          throw err;
        }

        bcrypt.compare(pass_db, hash, function (err, result) {
          if (err) {
            throw err;
          }
          console.log(result);
        });
      });

I hope you can help with this problem, thanks.

1

There are 1 best solutions below

0
On

As long as the password being stored in the db is retrieved properly it should work. I simplified the program to not use a database (just a local object to store the hashed password) and it works fine. Since I'm using the same bcrypt commands you are, the only thing I can imagine is that there's a problem with the hashed password not coming back from the database properly. Try printing out the hashed value during create and again after retrieving from the db and confirm they match. If pass_db is not exactly what it should be, that would explain why you can't compare successfully. Are you positive that result[0] coming back from the db.query is a JSON object that has a password attribute?

Here's my simplified version of the code that works without using the db:

const bcrypt = require('bcryptjs')
const passwords = {};

const create = async (email, password) => {
  if (password.length < 6) {
    console.log("Password must be at least 6 characters");
  } else {
    const hash = bcrypt.hashSync(password, 6);
    passwords[email] = hash;  // Store the hash in the passwords instead of db
  }
};

const login = (email, password) => {
  const pass_db = passwords[email];  // Retrieve hash from passwords instead of db
  if (pass_db) {
    const validate = bcrypt.compareSync(password, pass_db);
    if (validate) {
      console.log('Correct login');
    } else {
      console.log('Incorrect email or password');
    }
  } else {
    console.log('Incorrect email or password');
  }
};

const email = '[email protected]';
const pw = 'testpass12345';
create(email, pw);
console.log('Try the right password');
login(email, pw);
console.log('Try the wrong password');
login(email, 'wrongpw');
console.log('Try the wrong email');
login('[email protected]', 'blah');

Running this program gives the following output:

Try the right password
Correct login
Try the wrong password
Incorrect email or password
Try the wrong email
Incorrect email or password