On the callback from Facebook for nodejs passport authentication, how do you get the req
object within the callback?
passport.use(new FacebookStrategy({
clientID: 123456789,
clientSecret: 'SECRET',
callbackURL: "http://example.com/login/facebook/callback"
},
function(accessToken, refreshToken, profile, done){
// Is there any way to get the req object in here?
}
));
Setting the passReqToCallback
option, as so:
passport.use(new LocalStrategy({ passReqToCallback: true },
function(req, username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) {
req.flash('error', 'Your password is too long');
req.flash('error', 'Also, it is too short!!!');
return done(null, false);
}
return done(null, user);
});
}
));
req
becomes the first argument to the verify callback
As per https://github.com/jaredhanson/passport/issues/39
I am answering it too late, but i think my solution is better and more conventional. In the official documentation here. There is a section "Association in Verify Callback", in which it is mentioned that if we set the strategy's passReqToCallback option to true, this enables req and it will be passed as the first argument to the verify callback.
So my FacebookStrategy now looks like:
var User = require('../models/UserModel.js');
var FacebookStrategy = require('passport-facebook').Strategy;
exports.facebookStrategy = new FacebookStrategy({
clientID: 'REPLACE_IT_WITH_CLIENT_ID',
clientSecret: 'REPLACE_IT_WITH_CLIENT_SECRET',
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);
});
});
}
});
}
);
In my code sample i have added some logic to save user info in DB and saving user details in session. I thought it might be helpful to people.
req.user gives the information of user stored in passport session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With