mahdi pishguy mahdi pishguy - 4 months ago 14
Node.js Question

NodeJs check username and password return null

I'm trying to check the entered username and password stored in a database.
My solution is not correct and I think there might be something better than my code.

Here it is thus far:

function login (username, password, callback) {
var query = "SELECT * FROM users WHERE username = ?";

connection.query(query, [username], function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
var user = results[0];

if (!bcrypt.compareSync(password, user.password)) {
return callback();
}

callback(null, {
id: user.id.toString(),
});

});
}
app.get('/salam', function (req, res) {
var username = 'mahdi';
var originalPassword = 'a';

login(username , originalPassword,function (callback) {
console.log(callback);
});
});


In my code,
console.log(callback);
returns null, but usernames and passwords are correct. How can I fix this?

Answer

In your success callback function, you are having 2 arguments but in error callback, only one argument.

In error and success case, value of first parameter will always be null and in if (!bcrypt.compareSync(password, user.password)) { case, value of first argument will be undefined as there is no value being passed as argument.

Suggestion: Use first argument as Boolean(false or true) and based on the value, handle the callback.

function login(username, password, callback) {
  var query = "SELECT  * FROM users WHERE username = ?";

  connection.query(query, [username], function(err, results) {
    if (err) return callback(false);
    if (results.length === 0) return callback();
    var user = results[0];

    if (!bcrypt.compareSync(password, user.password)) {
      return callback(false);
    }
    callback(true, {
      id: user.id.toString(),
    });

  });
}
app.get('/salam', function(req, res) {
  var username = 'mahdi';
  var originalPassword = 'a';

  login(username, originalPassword, function(success, value) {
    if (success) {
      console.log(value);
    }
  });
});

Comments