Error data and hash arguments required

bcrypt compare takes 3 parameters passwordToCheck passwordHash and a callback respectively Check the documentation for examples This error means one

I am getting a bcrypt error stating that data and hash arguments are required, referencing line #44 in my routes.js file. From what I can tell, I am passing that information: the first parameter to bcrypt.compare is the user entered password, and the second is the hashed password retrieved from the db. What am I doing wrong?

bcrypt.compare(req.params.password, user.password, function...

routes.js

'use strict'

var express = require('express');
var router = express.Router();
var User = require('../app/models/user');
//password hashing
var bcrypt = require('bcrypt');

var count = 0;

router.use(function(req, res, next) {
    count++;
    console.log('API hit count = %s', count);
    next();
});

// /users post(create new user) get(specific user)
router.route('/users')
    .post(function(req,res) {
        var user = new User();
        user.username = req.body.username;
        user.password = bcrypt.hashSync(req.body.password, 10);

        //save the user and checkfor errors
        user.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                res.json({message: "User created!"});
            }    
        });

    })

router.route('/users/:username')
    .get(function(req, res) {
        var query = {
            username: req.params.username,
        };
        User.findOne(query, function(err, user) {
            if (err) { 
                res.send(err);
            } else {
                bcrypt.compare(req.params.password, user.password, function(err, res) {
                    if(err) {
                        console.log('Comparison error: ', err);
                    }
                })
                res.json(user);
            }
        });
    })
1) Solution

bcrypt.compare takes 3 parameters; passwordToCheck, passwordHash, and a callback, respectively. (Check the documentation for examples)

This error means one or both of the first 2 parameters are either null or undefined. Therefore, make sure both of them are passed correctly. (Not as null or undefined)

2) Solution

Why do we face this error?
bcrypt Error: data and hash arguments required

Example:
bcrypt.compare(first, second)

Ans:
because either second key hash password does not exist (null or undefined) or first, which are compared to each other.

3) Solution

I used

const user = await User.find({email: req.body.email}) //which returned all users

//and unless i reference the first user in index 0, i can’t pass user.password to the //bcrypt compare method because it’s not a string
I changed it to

await User.findOne({email: req.body.email})//from which i can use user.password in the //bcrypt compare method
4) Solution
const passwordMatch = await bcrypt.compare(password, user.password);

Make sure you are giving raw password and hash password. This will return a boolean value.

5) Solution

I was having the same error when I was working with node js and mongoose. It was caused by attribute added to password called select: false in user model.

After remove it, it works.

6) Solution

I had the same error and the problem was a missing await when calling the function that reads from database

7) Solution

the steps for this problem :
1-ensure that the bcrypt function is have awir before it
2- if the problem is still exist ,then the problem is in the database (mongodb),try to create new database
an example:

const match = await bcrypt.compare(password,userValid.password);
            if (match) {
                res.send("login successful")
            }else{
                res.send("wrong password")
            }
        }
8) Solution

I was having the same issue, but I was using the synchronous form of bycrypt.compare(), which is bcrypt.compareSync(), so I changed it to bcrypt.compare() and it works perfectly.

9) Solution

Use

findOne({})

instead of

find()

Try console.log() to view and verify the data.

10) Solution
try {
    let match  = await bcrypt.compare(password, user.password)
    if(!match){
        return  res.json({mass: "invalid Created"})
    }else{
       res.send('Wrong password')
    }

    console.log('success fulli', user)
    res.render('pages/auth/login', {title: 'Login In Your Account'})

} catch(e) {
    console.log(e)
    next(e)
}
11) Solution

The problem also can appear when you forget to add await when loading data from the database.
I got the same error after forgetting to add «await».

let user = User.findOne({ username: req.body.username });

let user = await User.findOne({ username: req.body.username });

12) Solution

I also have this problem i set for password select:false in user model and solved by adding select('+password') to login route

13) Solution

i know all the questions are solved but maybe someone finds this code works for him

const passwordMatch = await bcrypt.compare(password, user.rows[0].s_password);

The name after the dot it’s the name you use in your database, it’s the field

Comments Section

Set a breakpoint right before bcrypt.compare is called and see what req.params.password and user.password are.

@bejado Dammit, I had a mistake in my app.js, sending in an undefined password. Thanks for helping.

This can also happen when you are using arrow function syntax, instead of normal function() syntax. So, make sure to use the latter syntax if you want to preserve this coming from the model, i.e., when pulling something out of the current schema. This saved my day. Thanks!!!

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don’t require clarification from the asker.

The await syntax does not require the third argument. My issue was one of the two arguments did not have the value I expected, so fixing that fixed this issue.

Btw i’m using flutter and nodejs

Related Topics
javascript
bcrypt

Mentions
Ethan
Sapy
Riccardo
Ncutixavier
U Ways
Mirza Hayat
Caffeines
Ahmed Elbltagy
Kolade Chris
Ahmed El Beltagy
Mahyar Mottaghi Zadeh
Freenine
Natnael Tibebu
Ali Bin Naseer
Mza
Cursorrux
Zobaidul Kazi
Freedisch
Roel Leal

References
stackoverflow.com/questions/42241113/bcrypt-error-data-and-hash-arguments-required

I’ve done some investigation using console.log() statements (not proud of it) but I think I’ve managed to find out the issue. If we add in the the first console log statement here:

  app.post('/register', checkNotAuthenticated, async (req, res) => {
    try {
      console.log("BCRYPT COMPARE RUNS HERE")
      const hashedPassword = await bcrypt.hash(req.body.password, 10)
      const newUser = new User({
        id: Date.now().toString(),
        name: req.body.name,
        email: req.body.email,
        password: hashedPassword
      })
      res.redirect('/login')
      console.log(newUser)
    } catch {
      res.redirect('/register')
    }

and the second one here:

 const initializePassport = require('./passport-config')
  initializePassport(
    passport,
    email => User.find({email: email}).then((result) => { console.log("USER DATA EXTRACTED HERE") }).catch((err) => { console.log(err) }),
    id => User.find({id: id})
  )

The next time you click on login, you should see an output like:

Listening on port 3000
BCRYPT COMPARE HAPPENING
Error: data and hash arguments required
...
...
...
USER DATA EXTRACTED HERE

Notice that bcrypt.compare is being run before we are actually able to grab the user information from the DB? This means that all the arguments into that function are null, which is what is returning that error. Now, I’m no JS expert, but this can be fixed with an await statement added here:

   function initialize(passport, getUserByEmail, getUserById) {
      const authenticateUser = async (email, password, done) => {
        const user = await getUserByEmail(email)
        if (user === null) {
          return done(null, false, { message: 'No user with that email' })

        }

Which makes sure that the user info is queried from the DB before moving along in the script.

Any ideas why I’m getting the error

(node:21964) UnhandledPromiseRejectionWarning: Error: data and hash arguments required

on line

const password = await bcrypt.compare(req.body.password);

full code:

const User = require('../models/user')
const bcrypt = require('bcrypt')
const register_index = (req, res) => {
res.render('auth/register', {title: 'Register'})
}
const register_store = async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const user = new User({
first_name: req.body.first_name,
surname: req.body.surname,
email: req.body.email,
username: req.body.username,
addnumber: req.body.addnumber,
addstreet: req.body.addstreet,
addpostcode: req.body.addpostcode,
contact: req.body.contact,
password: hashedPassword,
})
user.save();
res.status(201).send();

} catch(error) {
console.log(error)
res.send(500).send();
}
}
const login_index = (req, res) => {
res.render('auth/login', {title: 'login'})
}
const login_auth = async (req, res) => {
const email = req.body.email;
const password = await bcrypt.compare(req.body.password);
const user = User.findOne({
email: email,
password: password,
})
try {
if(!user) {
return res.status(400).send("We don't have a user with that email")
} else {
res.status(200).send('Success')
}
} catch(error) {
res.status(500).send('Server Error');
}

}

module.exports = {
register_index,
register_store,
login_index,
login_auth,
}

Когда вы вызываете функцию bcrypt.compare (), вам необходимо убедиться, что вы указали и пароль, и хешированный пароль. Так что положите туда распечатку и посмотрите, что вам не хватает.

Случай 1: req.param (‘пароль’) по какой-то причине пуст (имя поля в вашей html-форме может содержать опечатку)

Случай 2: user.encryptedPassword пуст. В этом случае причина может заключаться в том, что вы не шифруете свой пароль при создании / обновлении своей пользовательской записи. Чтобы убедиться, что вы это делаете, откройте свою базу данных и после создания нового пользователя проверьте запись в БД и посмотрите, есть ли там ваш encryptedPassword. Вот пример того, как вы можете зашифровать пароль во время создания / обновления:

В вашей модели User у вас могут быть следующие функции:

beforeUpdate: function (values, next) {
    if (values.password) {
        bcrypt.hash(values.password, 10, function (err, hash) {
            if (err) {
                return next(err);
            }
            values.encryptedPassword = hash;
            next();
        });
    }
},

beforeCreate: function (values, next) {
    bcrypt.hash(values.password, 10, function (err, hash) {
        if (err) {
            return next(err);
        }
        values.encryptedPassword = hash;
        next();
    });
}

Обратите внимание на эту строку:

values.encryptedPassword = hash;

Поскольку у вас нет атрибута пароля в схеме, предоставленный файл values.password не будет нигде сохранен. Другая вещь в вашем случае может заключаться в том, что вы нигде не устанавливаете encryptedPassword. Таким образом, другой подход — изменить вашу схему и переименовать encryptedPassword в простой пароль, а затем заменить

values.encryptedPassword = hash;

С участием

values.password = hash;

I have a user log system that works well, instead when comparing the hash of the database with the introduction in a html field throws me the following error

Error: data and hash arguments required

I am sending 3 parameters just as it says in the documentation, which is the password in plain text, the hash and a callback. Thank you in advance

'use strict';

const bcrypt = require('bcrypt')

module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
allowNull: false,
type: DataTypes.STRING,
unique: true
},
password_hash: DataTypes.STRING,
password: DataTypes.VIRTUAL
}, {});

User.login = (email, password) => {
return User.findOne({
where: {
email: email
}
}).then(user => {
if(!user) return null
return user.authenticatePassword(password).then(valid => valid ? user : null)
})
}

/* =============== /
/
METODO PARA COMPARAR HASH /
/
=============== */

User.prototype.authenticatePassword = (password) => {
return new Promise((res, rej) => {
bcrypt.compare(password, this.password_hash, (err, valid) => {
if(err) return rej(err)

  res(valid)
})

})
}

User.associate = function(models) {
// associations can be defined here
};
User.beforeCreate((user, options) => {
return new Promise((res, rej) => {
if(user.password) {
bcrypt.hash(user.password, 10, (err, hash) => {
user.password_hash = hash
res()
})
}
})
})
return User;
};

Понравилась статья? Поделить с друзьями:
  • Error dagger does not support injection into private fields
  • Error daemon not started
  • Error da file missing please check
  • Error d3dx9 43 dll
  • Error d3d9 dll