문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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);
    }
  });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top