Search code examples
facebooksails.jspassport.jspassport-facebook

Unable to receive email address in sailsjs from passportjs


I'm unable to get the email address from facebook when i'm making the following call...

// https://developers.facebook.com/docs/
// https://developers.facebook.com/docs/reference/login/
facebook: function(req, res) {
  passport.authenticate('facebook', { scope : ['email'] }, function(err, user) {
  req.logIn(user, function(err) {
    if (err) {
      return;
    }

    res.redirect('/');
    return;
  });
 })(req, res);
},

This is how the response is handled and is basically the PassportJS docs code.

customMiddleware: function(app) {

  passport.use(new FacebookStrategy({
    clientID: "5xxxxxxxxxxxxx6",
    clientSecret: "exxxxxxxxxxxxxxxxxxxxxxxxxxxd9",
    callbackURL: "http://localhost:1337/auth/facebook/callback"
  }, verifyHandler));

  app.use(passport.initialize());
  app.use(passport.session());
}

And here is the handler.

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


var verifyHandler = function(token, tokenSecret, profile, done) {
   process.nextTick(function() {
   sails.log.info(profile);
   Serviceseeker.findOne({uid: profile.id}, function(err, serviceseeker)                {
       if (serviceseeker) { 
          return done(null, serviceseeker); 
       } 
       else {
          var data = {
             provider: profile.provider,
             uid: profile.id,
             name: profile.displayName
          };

          if (profile.emails && profile.emails[0] && profile.emails[0].value) {
             data.email = profile.emails[0].value;
          }
          if (profile.name && profile.name.givenName) {
             data.firstName = profile.name.givenName;
          }
          if (profile.name && profile.name.familyName) {
             data.lastName = profile.name.familyName;
          }

          Serviceseeker.create(data, function(err, serviceseeker) {
             return done(err, serviceseeker);
          });
       }
     });
   });
 };

And this is the response that I'm getting

info: info: { id: '1xxxxxxxxxxxxxx9',
              username: undefined,
              displayName: 'Txxxx Slxxxxn',
          name:
            { familyName: undefined,
              givenName: undefined,
              middleName: undefined },
          gender: undefined,
          profileUrl: undefined,
          provider: 'facebook',
          _raw: '{"name":"Txxxx Slxxxxn","id":"1xxxxxxxxxxxxxx9"}',
          _json: { name: 'Txxxx Slxxxxn', id: '1xxxxxxxxxxxxxx9' } }

Solution

  • Did you try:

     passport.use(new FacebookStrategy({
            clientID: 'CLIENT_ID',
            clientSecret: 'CLIENT_SECRET',
            callbackURL: "http://www.example.com/auth/facebook/callback"
            passReqToCallback : true,
            profileFields: ['id', 'emails', 'name'] //This
        },