passportjs中间件未使用错误 - 使用expressjs,bookshelf,express-session

时间:2015-03-19 22:08:04

标签: express passport.js bookshelf.js

我试图用sqlite3 / bookshelf.js模块实现passport.js模块。这是我的部分代码:

var session = require('express-session');
app.use(session({
  secret: 'secret cat',
  proxy: true,
  resave: true,
  saveUninitialized: true
 }));

 var User = bookshelf.Model.extend({
    tableName: 'users'
 });

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

passport.use(new LocalStrategy(function(username, password, done) {
  new User().where({username: username, password: password}).fetch()
  .then(function(user){
    if (user === null) {
        return done(null, false, {message: 'Invalid username or password'});
    }
    return done(null, user.toJSON());
  });
}));

app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true }));

以下是我的所有依赖项:

"dependencies": {
 "bluebird": "^2.9.14",
 "body-parser": "~1.10.2",
 "bookshelf": "^0.7.9",
 "cookie-parser": "~1.3.3",
 "debug": "~2.1.1",
 "express": "~4.11.1",
 "express-session": "^1.10.4",
 "hbs": "~2.8.0",
 "knex": "^0.7.6",
 "morgan": "~1.5.1",
 "passport": "^0.2.1",
 "passport-local": "^1.0.0",
 "serve-favicon": "~2.2.0",
 "sqlite3": "^3.0.5"
}

如果我写错了用户名和密码,我会被正确重定向。但是,如果我使用正确的数据登录,则会收到此错误:

Unhandled rejection Error: passport.initialize() middleware not in use 
at IncomingMessage.req.login.req.logIn

任何想法我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

啊,刚发现它的文档:在基于Connect或Express的应用程序中,需要使用passport.initialize()中间件来初始化Passport。

http://passportjs.org/guide/configure/