使用节点js中的passport-local模块验证(登录)密码时出错

时间:2015-04-02 13:46:35

标签: javascript node.js express mongoose passport.js

Server running at http://localhost:3000/

/home/sankar/Cloud/config/strategies/local.js:26
        if (!(user.authenticate(password))) 
                   ^
TypeError: Object { firstName: 'raju',
lastName: 'raju',
email: 'raju@070',
username: 'raju',
password: 'raju',
_id: 551b7ca79177c00c1342a3ee,
__v: 0 } has no method 'authenticate'
 at Promise.<anonymous>                 (/home/sankar/Cloud/config/strategies/local.js:26:15)
  at Promise.<anonymous>      (/home/sankar/Cloud/node_modules/mongoose/node_modules/mpromise/lib/promis       e.js:177:8)
  at Promise.EventEmitter.emit (events.js:95:17)
  at Promise.emit (/home/sankar/Cloud/node_modules/mongoose/node_modules/mpromise/lib/promis       e.js:84:38)
  at Promise.fulfill (/home/sankar/Cloud/node_modules/mongoose/node_modules/mpromise/lib/promis      e.js:97:20)
  at /home/sankar/Cloud/node_modules/mongoose/lib/query.js:1400:13
  at model.Document.init (/home /sankar/Cloud/node_modules/mongoose/lib/document.js:254:11)
  at completeOne (/home/sankar/Cloud/node_modules/mongoose/lib/query.js:1398:10)
  at Object.cb (/home/sankar/Cloud/node_modules/mongoose/lib/query.js:1155:11)
  at Object._onImmediate (/home/sankar/Cloud/node_modules/mongoose/node_modules/mquery/lib/utils.js      :137:16)

我只是在尝试使用正确的详细信息进行登录时才会收到此错误,这意味着错误的用户名会明确抛出错误,但不是因为没有正确的信誉。 它适用于SignUp。

Local.js代码:

   var passport = require('passport'),
   LocalStrategy = require('passport-local').Strategy,
   User = require('mongoose').model('User');

 module.exports = function()
 {
 passport.use(new LocalStrategy(function(username, password, done) 
 {
    User.findOne(
    {
        username: username
    },
    function(err, user)
    {
        if (err) 
        {
            return done(err);
        }
        if (!user) 
        {
            return done(null, false, 
            {
                message: 'Unknown user'
            });
        }
        if (!(user.authenticate(password))) 
        {
            return done(null, false, 
            {
                message: 'Invalid password'
            });
        }
        return done(null, user);
    });
  }));
  }

在我的user.js中,我添加了身份验证方法。

  UserSchema.methods.hashPassword = function(password) {
  return crypto.pbkdf2Sync(password, this.salt, 10000,
  64).toString('base64');
  };
  UserSchema.methods.authenticate = function(password) {
  return this.password === this.hashPassword(password);
  };

1 个答案:

答案 0 :(得分:0)

您尚未定义身份验证方法。将其附加到您的架构:

var user= mongoose.Schema({ 
    username: 'string',
    password: 'string'
});
authSchema.methods.authenticate = function( pwd ) {
    return ( this.password === pwd );
};
相关问题