2016-10-16 33 views
3

bcryptjsを使用してパスワードを比較しようとしているので、JWTに署名できますが、ログインしようとすると、トークンに署名してクライアントに送信できません。私はパスワードをハッシュし、私は.compare()メソッドを使用してhashパラメータで渡している問題を抱えているDBへ格納することができますBcryptjsがパスワードを比較できないNodejs

問題

。私はhashの値として何を渡すべきかについてはあまりよく分かりません。

技術:

  • NodeJS:5.4.1
  • bcryptjs:2.3.0
  • エクスプレス:4.14.0
  • ボディパーサー:1.15.2
  • のMongoDB。 3.2.5
  • マングース:4.6.1
パスワード中にエラーを取得

user.routes.js

var express  = require('express'); 
var router  = express.Router(); 
var jwt   = require('jsonwebtoken'); 
var bcrypt  = require('bcryptjs'); 
var salt  = bcrypt.genSaltSync(10); 
var config  = require('../config/database'); 

User = require('../models/user.model.js'); 

// Create new User 
router.post('/', function(req, res){ 
    var user = req.body; 
    if(!req.body.email || !req.body.password){ 
    res.json({success: false, message: 'Please pass email and password'}); 
    } else { 
    User.addUser(user, function(err, user){ 
     if(err){ 
     res.send(err); 
     } 
     bcrypt.genSalt(10, function(err, salt){ 
     bcrypt.hash(user.password, salt, function(err,hash){ 
     user.password = hash; 
     user.save(); 
     console.log('new user', user); 
     res.json({success: true, message: 'Create user successful'}); 
     }) 
     }) 
    }); 
    } 
}); 

は比較:

// Authenticate a User 
//email: [email protected] 
//password: password 
router.post('/login', function(req, res){ 
    User.findOne({ email: req.body.email }, function (err, user){ 
    if (err){ 
     res.send(err); 
    } 
    if(!user){ 
     res.json({ success: false, message: 'Authentication failed. User not found'}); 
    } else if (user) { 
     // where does this hash value get defined and passed in? 
     bcrypt.compare(req.body.password, hash, function(err, res){ 
     if(user.password != req.body.password){ 
      console.log('password incorrect'); 
     //res.json({ success: false, message: 'Authentication failed. Password incorrect'}); 
     } else { 
      var token = jwt.sign({ 
       email: user.email 
      }, config.secret, { 
      expiresIn: 60 // expressed in seconds 
      }); 
      console.log('token contents', token); 
      res.json({ 
      success: true, 
      message: 'Enjoy your token!', 
      token: token 
      }); 
     } 
     }); 
    } 
    }); 
}); 

答えて

2

あなたが比較メソッドに渡す必要があり、ハッシュ値は、あなたが呼び出されたときにあなたが得たものですbcrypt.hashメソッド。私はいくつかのDBのユーザーに関連付けられているそのハッシュを保存したと思いますので、そのハッシュを取得し、2番目のパラメータとしてメソッドを比較するために渡す必要があります。

私はcompareメソッドのコールバックで間違った比較をしていると思います。あなたはパスワードを比較するべきではありません、比較方法はあなたのためにそれを行います。 resがtrueかfalseであるかどうかを確認するだけです。真であれば、パスワードは同じで、それ以外の場合は異なっています。

あなたがこの記事の実装について詳しくは疑問を持っている場合は、そのことについて、非常に簡単な例があります。 https://solidgeargroup.com/password-nodejs-mongodb-bcrypt?lang=es

それは約束で書かれているが、それは理解することは非常に簡単です。

関連する問題