I using the Passport middleware for ExpressJS and I can't find a way to use both the passport-local strategy and the passport-facebook strategy together. I would like to set it up so that a user will create an account on my site and then, if they want to, they can log into facebook so you can see your friends who also are using the site. However I don't know what the logged in user is when the facebook api data is returned.
When someone creates an account, their data (username, email, ect..) is stored in the database. When they then log into facebook I would like to just update the database and the session to now include some of the info returned by the Facebook API (facebookID, AccessToken, etc..). How can this be achieved?
Here is the code that I can use to access the returned facebook data. The line with User.findOne only works if the database entry already has been synced with facebook before though. Is there any way that I can pass the req.session data to identify what the currently logged in user is and update their profile??
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: "http://localhost:3000/auth/facebook/callback",
//callbackURL: "http://localhost:3000"
profileFields: ['id', 'displayName']
},
function(accessToken, refreshToken, profile, done) {
User.findOne({facebookID: profile.id}, function(err, user) {
if (err) { return done(err); }
user.facebookID = profile.id;
user.facebookToken = accessToken;
user.save();
return done(null, user);
});
}
));
To get the currently logged in user, you need to add the passReqToCallback : true
option to the facebookStrategy
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: "http://localhost:3000/auth/facebook/callback",
//callbackURL: "http://localhost:3000"
profileFields: ['id', 'displayName'],
passReqToCallback : true // NEED THIS!!
},
function(req, accessToken, refreshToken, profile, done) {
if (req.user) {
User.findOne({username: req.user.username}, function(err, user) {
if (err) { return done(err); }
user.facebookID = profile.id;
user.facebookToken = accessToken;
user.save();
return done(null, user);
});
}
else{
console.log("attempted facebook auth from non-logged in user");
return done(null, null);
}
}
));