The single file index.js is working
var passport = require('passport');
var app = express();
....
app.use(passport.initialize());
app.use(passport.session());
app.route('/logout').get(function(req,res){
req.logout();
res.send('loggedout');
});
But when I make it into two files
//file1 index.js
var passport = require('passport');
var wrapper = require('./wrapper.js');
var app = express();
....
app.use(wrapper(app,passport));
// file2 wrapper.js
module.exports = function(app, passport){
return function(req, res, next){
app.use(passport.initialize());
app.use(passport.session());
app.route('/logout').get(function(req,res){
req.logout();
res.send('loggedout');
});
}
}
in this case it is not loggingout. And some times when I move logic into separate file, passport initialization is not working properly and I am getting "passport.initialize() middleware not in use" .
Tell me the way I can wrap passport such that ..all initialization and sessions are handled in another file (I mean module) so that in source file I can use the wrapper without initializing passport.
In short the pattern to wrap passportjs
Your current code adds the passport initialize and session middleware on each incoming request. They are added at the end of your middleware stack and therefore are probably never called. Your requests are also never get beyond this middleware, since you do not call the next
method. You also build a memory leak.
Your code could look like (untested, just written down):
var passport = require('passport')
module.exports = function(app) {
app.use(passport.initialize())
app.use(passport.session())
app.route('/logout').get(function(req, res) {
req.logout()
res.send('loggedout')
})
}
Usage:
var app = express();
require('./passport-stuff')(app)
Note: You can require('passport')
in multiple files and they all get the same instance. That is, you don't have to provide passport do other files.