Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport-facebook doesn't get email [duplicate]

I have already implemented the Facebook-LogIn in my website with express js and passport-Facebook. It works well (I get field profile), but the problem is that I don't get the Email. I get an error:

email   : profile.emails[0].value,

TypeError: Cannot read property '0' of undefined

My code:

passport.use('facebook',new FacebookStrategy({
        clientID            : config.facebook.id,
        clientSecret    : config.facebook.secret,
        callbackURL  : '/auth/facebook/callback',
        profileFields : ['id', 'displayName', 'emails','photos']
    }, function(accessToken, refreshToken, profile, done) {

        User.findOne({provider_id: profile.id}, function(err, user) {
            if(err) throw(err);
            if(!err && user!= null) return done(null, user);

            var user = new User({
                provider_id : profile.id,
                name                 : profile.displayName,
                email               : profile.emails[0].value,
                photo               : profile.photos[0].value,
            });
            user.save(function(err) {
                if(err) throw err;
                return done(null, user);
            });
        });
    }));

It would be great if someone could help me with the solution to my problem :)

like image 287
jcabello Avatar asked Sep 14 '14 11:09

jcabello


2 Answers

I had the same problem. We had 10 test users, all 10 had email addresses associated with their Facebook account. But for one of the 10 testers, Facebook did not return the 'email' JSON property in the profile response. I have no idea why, since it looked identical to other Facebook profiles that worked fine.

The fix was to change this line:

passport.authenticate('facebook')

To this:

passport.authenticate('facebook', { scope: [ 'email' ] })

I still can't explain why it worked for 9/10, but not for one. Either way, it's fixed now :-)

like image 174
Alex York Avatar answered Sep 27 '22 23:09

Alex York


Try this passport.authenticate('facebook', { scope: [ 'email' ] })

Also add a new field profileFields: [ 'email' , 'name' ] in the facebookStrategy

like image 45
Ajay Avatar answered Sep 27 '22 21:09

Ajay