Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare passwords BcryptJS

So I'm trying to build a very basic user login. I'm trying to create a user, then login with those credentials and get back a JSON Web Token. Where I'm stuck is trying to compare the passwords then send a response.

Steps:

Create User:

  1. enter email and password
  2. salt/hash user password
  3. store user into database
  4. return success

Login

  1. find user by request email value
  2. if found compare passwords
  3. passwords good send JSON Web Token

User Model

email:{ 
  type: String,
  required: true,
  unique: true
},
password: {
  type: String,
  required: true
}

User Routes

var express     = require('express');
var router      = express.Router();
var jwt         = require('jsonwebtoken');
var bcrypt      = require('bcryptjs');

// Create User
...
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("superSecret", salt, function(err, hash) {
      user.password = hash;
      user.save();
      res.json({success: true, message: 'Create user successful'});
    });
  });
...

// Login
...
bcrypt.compare(req.body.password, 'superSecret', function(err, res) {
  if(req.body.password != user.password){
    res.json({success: false, message: 'passwords do not match'});
  } else {
    // Send JWT
  }
});

So the two problems here is that, I can't send a response nor can I compare the password. Just completely stuck on this, any help would be greatly appreciated.

like image 399
wsfuller Avatar asked Oct 16 '16 23:10

wsfuller


People also ask

Should I use bcrypt or Bcryptjs?

Sync functions. Bcrypt is 3.1 times faster than bcryptjs in generating hash passwords and 1.3 times faster in comparing function.

How secure is Bcryptjs?

Is bcryptjs safe to use? The npm package bcryptjs was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use. See the full health analysis review.

How does node JS compare with bcrypt password?

Check A User Entered Password const bcrypt = require("bcryptjs") const passwordEnteredByUser = "mypass123" const hash = "YOUR_HASH_STRING" bcrypt. compare(passwordEnteredByUser, hash, function(err, isMatch) { if (err) { throw err } else if (! isMatch) { console. log("Password doesn't match!") } else { console.


1 Answers

As described in the doc, you should use bcrypt.compare like that:

bcrypt.compare(req.body.password, user.password, function(err, res) {
  if (err){
    // handle error
  }
  if (res)
    // Send JWT
  } else {
    // response is OutgoingMessage object that server response http request
    return response.json({success: false, message: 'passwords do not match'});
  }
});

And here is a nice post about Password Authentication with Mongoose (Part 1): bcrypt

like image 93
L_K Avatar answered Sep 17 '22 21:09

L_K