Question

I am currently building out the Authentication piece of my Sails.js app, using bcrypt to hash my passwords. Everything is working well, here is a sample of the implementation thus far:

beforeCreate: function (values, next) {

    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {

        if (err) return next(err);

        values.password = encryptedPassword;
        next();

    });

}

Now, both in my model and in my controller, I am using require('bcrypt') or var bcrypt = require('bcrypt'); so I can use it within my class.

I am looking for a better practice way of defining var bcrypt = require('bcrypt'); once and globally so that I can simply use the bcrypt variable whenever I need to (inside other models or controllers).

I am inclined to believe that Sails.js already has something in place for that? If not, what do you suggest the best route of implementation? In the end, I am looking for best practice.

Thanks in advance!

Was it helpful?

Solution

Since Node.js modules are cached once they are loaded for the first time, reusing require('bcrypt') or not won't make any difference in terms of performance.

That said, if you are still up for doing it your way, you can require bcrypt in config/bootstrap.js and add it to the sails namespace:

module.exports.bootstrap = function (cb) {
  sails.bcrypt = require('bcrypt');

  //...

  cb();
}

After that you'll be able to use sails.bcrypt in your controllers or models.

OTHER TIPS

You can also do this by utilizing globals

module.exports.globals = {
    bcrypt : require('bcrypt')
}

and in the application code, refer it like below

sails.config.globals.bcrypt.hash(password, saltRounds, function (err, hash) {
    if (!err) {
      sails.config.globals.logger.info('creatHash-hash-->', hash);
      return cb(null, hash);
    } else {
      return cb(err);
    }
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top