【问题标题】:Promisifying bcrypt-nodejs with Bluebird用 Bluebird 承诺 bcrypt-nodejs
【发布时间】:2016-02-23 15:33:06
【问题描述】:

我正在使用 NodeJS、bcrypt-nodejs (https://github.com/shaneGirish/bcrypt-nodejs) 和 Bluebird 进行承诺。想出了这段代码,并想知道是否有更好的方法来做同样的事情。我有模块:

var Promise = require("bluebird"),
    bcrypt = Promise.promisifyAll(require('bcrypt-nodejs'));

// ....[some othe code here]

    Users.prototype.setPassword = function(user) {

        return bcrypt.genSaltAsync(10).then(function(result) {
            return bcrypt.hashAsync(user.password, result);
        });

    };

然后我从另一个模块调用users.setPassword,如下所示:

app.post('/api/v1/users/set-password', function(req, res, next) {
    users.setPassword(req.body).then(function(result) {

        // Store hash in your password DB.
        console.log(result[1]);

        res.json({
            success: true
        })
    })
        .catch(function(err) {
            console.log(err);
        });
});

它总是以“[错误:没有给出回调函数。]”消息结束,因为bcrypt.hashAsync 似乎需要 4 个参数。原始的、非承诺的 hash 方法只需要 3 个。当我向hashAsync 添加空回调时,它工作正常:

Users.prototype.setPassword = function(user) {

    return bcrypt.genSaltAsync(10).then(function(result) {
        return bcrypt.hashAsync(user.password, result,function() {});
    });

};

有没有更好的方法来做到这一点,而不像上面那样提供空回调?

编辑:

响应Bergi的评论..该功能最终会设置密码,我只是在发布问题时没有那么远。现在已经到这里了,如果有什么不对的地方请告诉我:

 Users.prototype.setPassword = function(user) {


        return bcrypt.genSaltAsync(10).then(function(result) {
            return bcrypt.hashAsync(user.password, result, null);
        })
        .then(function(result) {
                // store in database
                console.log("stored in database!");
                return result;
            });

    };

【问题讨论】:

  • 我肯定会使用不同的方法名称。 users.setPassword 似乎没有设置密码,只是计算给定密码的哈希值。

标签: javascript node.js promise bluebird


【解决方案1】:

bcrypt.hashAsync 似乎需要 4 个参数。原始的、非承诺的哈希方法只需要 3 个。

恰恰相反。来自the docs

hash(data, salt, progress, cb)

  • data - [必需] - 要加密的数据。
  • salt - [必需] - 用于散列密码的盐。
  • progress - 在哈希计算期间调用的回调以表示进度
  • callback - [必需] - 数据加密后触发的回调。

原始方法接受 4 个参数,hashAsync 将接受 3 个并返回一个承诺。

但是,在您的代码中,您只传递了两个。不过,您不需要传递一个空函数,该参数不是 [REQUIRED] 意味着您可以为其传递 null (或任何其他虚假值)。 bcryptwill create such an empty function itself。所以使用

function (data) {
    return bcrypt.genSaltAsync(10).then(function(result) {
        return bcrypt.hashAsync(data.password, result, null);
    });
}

【讨论】:

  • 在promisified 版本中也可能需要支持progress,方法是将其作为function (data) 的第二个参数接受。
【解决方案2】:

这是我不久前做的一个项目中承诺的 bcrypt。对于这么小的、简单的库,Bluebird 并不是必需的。

module.exports = {
   makeUser: function(username, password){
    return new Promise(function(resolve, reject) {
      bcrypt.genSalt(10, function(err, salt){
        bcrypt.hash(password, salt, null, function(err, hash) {
          if (err) {
            console.log("hashing the password failed, see user.js " + err);
            reject(err);
          }
          else {
            console.log("hash was successful.");
            resolve(hash);
          }
        })
      })
    })
    .then(function(hash){
      return db.createUser(username, hash)
    })
  },

  login: function(username, password){
    return db.userFind(username)
    .then(function(userObj){
      if(!userObj){
        console.log("did not find " + username + " in database.");
        return new Promise(function(resolve, reject){ 
          resolve({login:false, message:"Your username and/or password are incorrect."})
        }
      }
      else {
        console.log("found user: " + userObj._id, userObj);
        return new Promise(function(resolve, reject){
          bcrypt.compare(password, userObj.hashword, function(err, bool) {
            resolve({bool:bool, 
              user:userObj._id,
              mindSeal: userObj
            })
          })
        })
      } 
    })
  }
}

示例用法:

app.post('/signup', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  var user = handler.userExists(username)
  .then(function(answer){
    if (answer !== null){
      console.log(req.body.username + " was taken")
      res.send({login: false, message: req.body.username + " is taken"});
      return null;
    } else if (answer === null) {
      console.log("username not taken")
      return handler.makeUser(username, password);
    }
  })
  .catch(function(err){
    console.log("error during user lookup:", err);
    res.status(404).send({message:"database error:", error:err});
  })

  if (user !== null){
    user
    .then(function(x){
      console.log("this is returned from handler.makeUser: ", x)
      console.log(x.ops[0]._id)
      req.session.user = x.ops[0]._id;
      var mindSeal = { 
        userSettings: {
          username: x.ops[0]._id,
          newCardLimit: null,
          tValDefault: 128000000, 
          lastEdit: req.body.time, 
          todayCounter: 0,
          allTimeCounter: 0,
          cScaleDefault: {0: 0.9, 1: 1.2, 2: 1.8, 3: 2.5},
          accountMade: req.body.time
        },
        decks: {}
      };
      handler.setMindSeal(req.session.user, mindSeal, req.body.time);
      res.send({
        login: true, 
        mindSeal: mindSeal
      });
    })
    .catch(function(error){
      console.log("make user error: " + error);
      res.status(401).send({message:"failed.",error:error,login:false});
    })
  }

});

app.post('/login', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  handler.login(username, password)
  .then(function(obj){
    if (obj.bool){
      console.log("username and password are valid. login granted.");
      req.session.user = obj.user;
      console.log("obj is:", obj)
      var mindSeal = {decks:obj.mindSeal.decks, userSettings:obj.mindSeal.userSettings};
      console.log("mindSeal sending:", mindSeal);
      res.status(200).send({
        login: true, 
        message:"Login Successful", 
        mindSeal: obj.mindSeal
      });
    }
    else {
      console.log("password invalid")
      res.status(401).send({login: false, message:"Your username and/or password are incorrect."})
    }
  })
  .catch(function(error){
    console.log(error);
    res.status(404).send({message:"database error:", error:err});
  })
});

仅概念示例;即时借用并稍微修改了我的一些旧代码。工作代码(我现在看到了我想改进的东西,但它可以工作)在这里:https://github.com/finetype/mindseal/blob/master/server.js

【讨论】:

    【解决方案3】:

    也许您可以使用another bcrypt library,它具有更好的 API,无需承诺。

    Users.prototype.setPassword = function(user) {
        return TwinBcrypt.hashSync(user.password, 10);
    };
    

    或者,使用进度跟踪:

    Users.prototype.setPassword = function(user) {
    
        function progress(p) {
            console.log( Math.floor(p*100) + '%' );
        }
    
        TwinBcrypt.hash(user.password, 10, progress, function(result) {
            // store in database
            console.log("stored in database!");
            return result;
        });
    
    };
    

    【讨论】:

    • 那个库怎么样?它似乎仍然具有异步模式,这将受益于使用承诺。
    • COI 披露(作者应该做出的):这个答案的作者是提到的“更好”的 bcrypt 库的作者。
    猜你喜欢
    • 2014-09-07
    • 2016-07-27
    • 1970-01-01
    • 2018-02-01
    • 2014-07-15
    • 2016-02-08
    • 1970-01-01
    • 2015-10-23
    • 2013-10-26
    相关资源
    最近更新 更多