2017-04-09 11 views
0

mongooseとbcryptを使用してログに記録しようとしました。 は、私はエラーを取得する:エラーログインMongooseとBcrypt

TypeError: cb is not a function

マイモデル:

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 
const bcrypt = require('bcrypt'); 
SALT_WORK_FACTOR = 10; 

const userSchema = Schema({ 
    email:{type: String, required: true}, 
    encrypted_password:{type: String}, 
    active:{type: Boolean}, 
    role_id:{ type: Schema.Types.ObjectId, ref: 'roles' ,required: true}, 
    create_date:{type: Date, default: Date.now}, 
}); 

userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) { 
    bcrypt.compare(candidatePassword, this.password, function (err, isMatch) { 
    if (err) { 
     return cb(err); 
    } 

    cb(null, isMatch); 
    }); 
}; 

const User = module.exports = mongoose.model('users',userSchema); 

私の認証方法:

const express = require('express') 
    , router = express.Router() 
const app = express(); 
const jwt = require('jsonwebtoken'); 
app.set('superSecret', 'XXXXXXX'); 

Users = require('./../database/models/people_culture/user'); 

module.exports = function(app){ 

app.post('/api/authenticate', (req, res) => { 
    Users.findOne({email: req.body.email}, function(err, user) { 
    console.log(user) 
    if (err) throw err; 

    if (!user) { 
     res.json({ success: false, message: 'Authentication failed. User not found.' }); 
    } else if (user) { 
password.' }); 
     var ismatch = user.comparePassword(req.body.password); 
     if(!ismatch){ 
     res.json({ success: false, message: 'Authentication failed. Wrong password.' }); 

     } else { 

     var token = jwt.sign(user, app.get('superSecret'), { 
      expiresIn: 1440 // expires in 24 hours 
     }); 

     res.json({ 
      success: true, 
      message: 'This is the key', 
      token: token 
     }); 
     } 

    } 

    }); 
}); 

app.use('/api', router); 
} 

は、私はいくつかのチュートリアルに従うと、常に同じエラーを取得します。 パスワードをハッシュする機能は正常に動作しますが、このエラーのためにパスワードを比較しようとするとログインできません。

私はExpress、Mongoose、JsonWebToken、およびbcryptを使用してユーザーを認証しています。

ありがとうございます。

答えて

0

まあ、そこにはいくつかのものがあります。まず、this.passwordをチェックしていますが、スキーマはencrypted_passwordと定義しています。また、私はあなたのパスワードを暗号化するためのロジックが表示されません。あなたのcomparePassword署名がfunction comparePassword(candidatePassword, cb)であることを

var ismatch = user.comparePassword(req.body.password); 

注:あなたが実際にコールバックを渡していないので、あなたが比較関数を実行するとき、それはだよう

最後に、エラーがあなたのルックスを見ています。

+0

私はあなたの提案のように関数を呼び出す方法を変更し、正常に動作します、ありがとう – joselegit

関連する問題