Get request object in Passport strategy callback
There's a passReqToCallback
option, see the bottom of this page for details: http://passportjs.org/guide/authorize/
Try this.
exports.facebookStrategy = new FacebookStrategy({
clientID: '.....',
clientSecret: '...',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
passReqToCallback: true
},function(req,accessToken,refreshToken,profile,done){
User.findOne({
'facebook.id' : profile.id
},function(err,user){
if(err){
done(err);
}
if(user){
req.login(user,function(err){
if(err){
return next(err);
}
return done(null,user);
});
}else{
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.name = profile.displayName;
newUser.facebook.token = profile.token;
newUser.save(function(err){
if(err){
throw(err);
}
req.login(newUser,function(err){
if(err){
return next(err);
}
return done(null,newUser);
});
});
}
});
}
);
User is a mongoose model, i save the user in DB.
For this reason instead of setting up the strategy when the application starts I usually setup the strategy when there is a request. for instance:
app.get(
'/facebook/login'
,passport_setup_strategy()
,passport.authenticate()
,redirect_home()
);
var isStrategySetup = false;
var passport_setup_strategy = function(){
return function(req, res, next){
if(!isStrategySetup){
passport.use(new FacebookStrategy({
clientID: ".....",
clientSecret: ".....",
callbackURL: "http://localhost:1337/register/facebook/callback",
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
// here you can access 'req'
.......
});
}
));
isStrategySetup = true;
}
next();
};
}
Using this you will have access to the request in your verification handler.