7

我正在使用 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;
            });

    };
4

3 回答 3

9

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

恰恰相反。从文档

hash(data, salt, progress, cb)

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

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

但是,在您的代码中,您只传递了两个。不过,您不需要传递一个空函数,该参数不是[REQUIRED]意味着您可以null为它传递(或任何其他虚假值)。bcrypt将自己创建这样一个空函数。所以使用

function (data) {
    return bcrypt.genSaltAsync(10).then(function(result) {
        return bcrypt.hashAsync(data.password, result, null);
    });
}
于 2014-07-18T08:09:56.337 回答
0

这是我不久前做的一个项目中承诺的 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

于 2016-02-23T07:15:00.707 回答
-5

也许您可以使用另一个 bcrypt 库,它具有更好的 API,从而消除了对 Promise 的需求。

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;
    });

};
于 2014-07-20T10:53:35.393 回答