简体   繁体   中英

How to pass a hashed password in a promise before posting it to the database using a Node.js server?

On a node.js server I am using bcrypt to hash a password which is received by a user via a POST request and then store the hash in a database. The hashing function function takes longer to compute than creation of the saving of the hash and other parameters to the database, so I need to use a promise to executing the save after the hashing function has finished. I am using the Q library for this purpose, but I'm not sure how to do this. I am using mongoose for data modelling.

async bcrypt hashing function

var bcrypt = require('bcrypt');
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(req.body.password, salt, function(err, hash) {
      // Store hash in DB
    });
  });
});

POST route

app.post('/api/users', function(req, res) {

  var newUser = new User({
    email: req.body.email,
    name: req.body.name,
    password: hash
  });

  newUser.save(function(err) {
    if(!err) {
      return res.send({ status: 'User created' });
    } else {
      if(err.name == 'ValidationError') {
        res.statusCode = 400;
        res.send({ error: 'Bad Request' });
      } else {
        res.statusCode = 500;
        res.send({ error: 'Internal Server Error' });
      }
    } 
  });
});

I would figure the population of the newUser variable and newUser.save() call would be the argument of then(), but how do I make the bcrypt hashing function issue the promise and pass the hash?

You could simply move your database queries, to inside the callback of the hash, so that when the hash call back is ready it would then save it.

var bcrypt = require('bcrypt');

app.post('/api/users', function(req, res) {
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(req.body.password, salt, function(err, hash) {
      var newUser = new User({
        email: req.body.email,
        name: req.body.name,
        password: hash
      });

      newUser.save(function(err) {
        if(!err) {
          return res.send({ status: 'User created' });
        } else {
          if(err.name == 'ValidationError') {
            res.statusCode = 400;
            res.send({ error: 'Bad Request' });
          } else {
            res.statusCode = 500;
            res.send({ error: 'Internal Server Error' });
          }
        } 
      });
    });
  });
});

Or use the synchronous call of bcrypt.hashSync but synchronous is not good practice when trying to work with Node.

But it could be like password: bcrypt.hashSync(req.body.password, salt)

If I understand correctly what you're asking, you want to save the user, after the password is hashed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM