2015-10-15 61 views
0

这是我如何散列并将我的密码存储在数据库中。使用节点j无法验证Express中的散列密码

NEWUSER功能

var salt = bcrypt.genSaltSync(10); 
var hash = bcrypt.hashSync(password, salt); 
var query="INSERT into user(email,firstname,lastname,logintime,gender,password) VALUES('"+email+"','"+firstname+"','"+lastname+"','"+logintime+"','"+gender+"','"+hash+"')"; 

这是我如何检索和检查,以验证

VALIDATE功能

var query = "SELECT password from user where email='" + email + "'"; 
connection.query(query,function(err,result){ 
    if(err) 
     { 
     console.log("ERROR:"+err.message); 
     } 
    else 
     { 
     if(result.length!==0) 

     { 

var hash=JSON.stringify(result[0].password); console.log(hash); 
    console.log(bcrypt.compareSync(password,hash)); 
if(bcrypt.compareSync(password, hash)) { callback(err, result); } 

这始终显示错误,但如果我这样做是显示预期结果

var hash = bcrypt.hashSync("sacjap", 8); 
      //var hash=JSON.stringify(result[0].password); 
      console.log(hash); 
      console.log(bcrypt.compareSync(password,hash)); 
      if(bcrypt.compareSync(password, hash)) 
       { 
      callback(err, result); 
       } 

所以问题是,每当我从数据库中得到的密码不起作用。 PLZ帮助

回答

0

首先,我的答案是基于我发现这里的文档上: https://github.com/davidwood/node-password-hash

看来,密码哈希模块试图调用你所提供的第二个参数的“分裂”功能'verify'函数,假设它是一个字符串(JavaScript String split function on MDN)。我认为你应该检查'result'变量的类型,它在我看来就像数据库返回的更复杂的查询结果对象。您提供的代码不会提供有关您在此处使用的连接类型的更多信息,因此我无法给出更具体的答案。我的方法是找出如何从'result'变量中得到一个简单的字符串,然后代表可以交给'verify'的散列密码。这只是一个疯狂的猜测,我希望这个小小的提示可以帮助你解决你的问题。

备注:您用于密码散列的模块似乎已被弃用,也许您应该寻找替代方案。

+0

感谢您的帮助。是的,你是对的。所以我改变了我的代码: –

+0

var hash = JSON.stringify(result [0] .password); \t \t \t \t console.log(hash); \t \t \t \t console.log(bcrypt.compareSync(password,hash)); \t \t \t \t如果(bcrypt.compareSync(密码,哈希值)) \t \t \t \t \t { \t \t \t \t回调(ERR,结果); \t \t \t \t \t} –

+0

但crypt.compare显示错误,即使当我把正确的密码。有什么想法吗? –