2014-07-18 19 views
6

ile bcrypt-nodejs promisifying NodeJS kullanıyorum, bcrypt-nodejs (https://github.com/shaneGirish/bcrypt-nodejs) ve sözler için Bluebird kullanıyorum. Bu kod ile geldi ve aynı şeyi yapmak için daha iyi bir yol olup olmadığını merak ediyorum.Bluebird

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

Her zaman ile biter: Ben aşağıda users.setPassword diyoruz başka modülünden sonra

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

    }; 

: Birlikte modülü var "[Hata:. Hiçbir geri çağırma işlevi verildi]" bcrypt.hashAsync olarak mesaj görünüyor 4 parametre gerektirir. Orijinal, promisified değil hash yöntemi sadece 3 gerektirir. Ben hashAsync boş geri arama eklediğinizde, iyi çalışıyor:

Users.prototype.setPassword = function(user) { 

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

}; 

Bunu yapmak için daha iyi bir yolu var mı yukarıdaki gibi boş geri arama sağlamadan?

DÜZENLEME: Bergi yorumuyla .. fonksiyon soru gönderdiniz zaman şifre sonunda, sadece o kadar alamadım koyacaktır cevaben

. Şimdi bu kadar ilerleme, bir şey olsa çok doğru değilse bana bildirin lütfen:

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

    }; 
+0

Farklı bir yöntem adı kesinlikle kullanacağım. 'users.setPassword' bir şifre koymuş gibi görünmüyor, ama sadece bir tane için bir hash hesaplıyor. Her zamanki gibi – Bergi

cevap

9

bcrypt.hashAsync seems to require 4 parameters. Original, non-promisified hash method requires 3 only though.

O yuvarlak yerine başka bir yoldur. the docs Gönderen:

hash(data, salt, progress, cb)

  • data - [REQUIRED] - the data to be encrypted.
  • salt - [REQUIRED] - the salt to be used to hash the password.
  • progress - a callback to be called during the hash calculation to signify progress
  • callback - [REQUIRED] - a callback to be fired once the data has been encrypted.

orijinal yöntem hashAsync 3 alıp bir söz dönecektir, 4 argümanları aldı. Bununla birlikte, kodunuzda sadece 2'yi geçiyordunuz. Bununla birlikte, boş bir işlevi geçmenize gerek yoktur, bu parametre [REQUIRED] değildir, bunun için null (veya herhangi bir diğer falsi değeri) iletebilirsiniz. bcrypt will create such an empty function itself. Yani Belki sözlere ihtiyacını ortadan kaldırır, daha iyi bir API ile, another bcrypt library kullanabilirsiniz

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

mükemmel cevap, thx! – spirytus

+0

Promisified sürümde 'progress'ı desteklemenin 'function (data)' içine ikinci bir argüman olarak kabul edilmesi de istenebilir. –

-5

kullanın. ilerleme takibi ile

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

Veya:

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

}; 
+1

Bu kütüphane nasıl daha iyi? Yine de vaatleri kullanmanın faydası olacak bir asenkron modu var gibi görünüyor. – Bergi

+5

COI Açıklama (yazarın yapmış olması gerekir): Bu cevabın yazarı, sözü edilen "daha iyi" bcrypt kütüphanesinin yazarıdır. –

0

Bu Bir süre önce yaptığımız bir proje benim promisified bcrypt olduğunu. Bluebird böyle küçük, basit bir kütüphane için gerçekten gerekli değildir.

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

Örnek Kullanım:

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

kavramsal örnek yalnızca; ödünç aldım ve biraz eski kodumu biraz değiştirdim. Çalışma kodu (Şimdi içinde geliştirmek istediğim şeyleri görüyorum, fakat işe yarıyor): https://github.com/finetype/mindseal/blob/master/server.js

İlgili konular