Search code examples
node.jsexpresspassport.jspassport-facebook

Retrieving photo from Facebook using passport-facebook


I am able to retrieve basic user information via passport-facebook, following the below code and saving in mongodb:

app.get("/auth/facebook", passport.authenticate("facebook", { scope : ["email", "publish_stream", "user_location", "user_hometown", "user_birthday", "read_friendlists"]}));

app.get("/auth/facebook/callback", passport.authenticate("facebook",{ successRedirect: '/', failureRedirect: '/'}));

var mongoose = require('mongoose'), 
FacebookStrategy = require('passport-facebook').Strategy, 
Users = mongoose.model('Users');

module.exports = function (passport, config) { 
passport.serializeUser(function(user, done) { 
    done(null, user.id);
}); 

passport.deserializeUser(function(id, done) { 
    Users.findOne({ _id: id }, function (err, user) { 
        done(err, user); 
    });
});

passport.use(new FacebookStrategy({ 
    clientID: config.facebook.clientID,
    clientSecret: config.facebook.clientSecret,
    callbackURL: config.facebook.callbackURL 
}, function(accessToken, refreshToken, profile, done) { 
    Users.findOrCreateFaceBookUser(profile, done);
}));};

However, I am not able to see the profile picture in the "profile".

The documentation https://github.com/jaredhanson/passport-facebook says to retrieve photos we need to pass the profileFields as below. But doing so, I am able to see the photo URL but loosing other data which were contained in _json e.g. profile._json.location.name. How can I retrieve photo with other user information intact?

passport.use(new FacebookStrategy({
// clientID, clientSecret and callbackURL
profileFields: ['id', 'displayName', 'photos', ....]},// verify callback));

Solution

  • Yes, the picture can be accessed via the graph api using the access token like this. "graph.facebook.com/"; + profile.username + "/picture" + "?width=200&height=200" + "&access_token=" + accessToken; There is no need to use the profile fields.