Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook Login is returning 'Undefined' Fields in user profile and it doesn't return email. MEANJs + Passport-facebook

I am using Meanjs.org boilerplate and Facebook Signup returns me to the Signup page. Following are the steps that I have taken so far.

1) Setting up the Facebook App Site URL

http://localhost:3000/

and the callback URI of OAuth

http://localhost:3000/auth/facebook/callback

2) Placing the APP_ID and APP_Secret in as Client_ID and Client_Secret

    facebook: {
    clientID: process.env.FACEBOOK_ID || '*****',
    clientSecret: process.env.FACEBOOK_SECRET || '*****',
    callbackURL: 'http://localhost:3000/auth/facebook/callback',
    profileFields: ['id','emails', 'first_name', 'last_name', 'displayName', 'link', 'about_me', 'photos' ]
},

3) Code is as follows

--Routes

// Setting the facebook oauth routes
app.route('/auth/facebook').get(passport.authenticate('facebook', {
    scope: ['email']
}));
app.route('/auth/facebook/callback').get(users.oauthCallback('facebook'));

-- The oauthCallback function,

    exports.oauthCallback = function(strategy) {
    return function(req, res, next) {
        passport.authenticate(strategy, function(err, user, redirectURL) {
            if (err || !user) {
                console.log('1' + err);
                //console.log(user);
                return res.redirect('/#!/signin');
            }
            req.login(user, function(err) {
                if (err) {
                    console.log('2' + err);
                    return res.redirect('/#!/signin');
                }

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

-- Passport-Facebook Strategy

module.exports = function() {
// Use facebook strategy
passport.use(new FacebookStrategy({
        clientID: config.facebook.clientID,
        clientSecret: config.facebook.clientSecret,
        callbackURL: config.facebook.callbackURL,
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, done) {

        console.log('facebook Strategy Started');
        // Set the provider data and include tokens
        var providerData = profile._json;
        providerData.accessToken = accessToken;
        providerData.refreshToken = refreshToken;

    //  console.log(JSON.stringify(profile));
        console.log(profile);

    //  console.log(JSON.stringify(profile.name.givenName));

        // Create the user OAuth profile
        var providerUserProfile = {
            firstName: profile.name.givenName,
            lastName: profile.name.familyName,
            displayName: profile.displayName,
            email: profile.emails[0].value,
            username: profile.username,
            provider: 'facebook',
            providerIdentifierField: 'id',
            providerData: providerData
        };

        //console.log('provider' + providerUserProfile);
        // Save the user OAuth profile
        users.saveOAuthUserProfile(req, providerUserProfile, done);
    }
));

};

4) Debugging

Logging err under oauthCallback function returns the following,

1TypeError: Cannot read property '0' of undefined

What Facebook returns as profile in Passport-Facebook module is as follows,

{ id: 'Id_of_the_person', username: undefined, displayName: 'Full_name_of_person', name: { familyName: undefined, givenName: undefined, middleName: undefined }, gender: undefined, profileUrl: undefined, provider: 'facebook', _raw: '{"name":"Full_name_of_person","id":"Id_of_the_person"}', _json: { name: 'Id_of_the_person', id: 'Id_of_the_person', accessToken: 'access_token_value', refreshToken: undefined } }

Can anyone be kind to guide me about getting the correct user profile from Facebook including user email?

Thank you so much.

like image 262
Hyder Avatar asked Aug 06 '15 15:08

Hyder


People also ask

Why can't I log in to my Facebook account?

Either way, not being able to log in to the Facebook account is a problem that needs to be solved. One way to fix the issue is to use the forgot password link that rests below the sign in box. I believe you have already tried that solution where a link to create a new password is sent to your email ID.

How to sign in to Facebook without email id?

Use your regular computer or smartphone to sign in instead if you have it on you now. Check your inbox for emails from Facebook asking you to approve the login. 2. Mobile Number Tips A lot of users have created their Facebook account using their mobile number instead of email ID.

Is it possible to recover a disabled Facebook account?

Not a pretty sight but entirely possible. Your Facebook account may have been disabled, but you should have been notified of the same. Check your inbox for any emails from Facebook. That will give you further insights into why the account was disabled. You should also notice a message informing you of the decision on the Facebook login page.

How to fix Facebook account sign-in issue?

One way to fix the issue is to use the forgot password link that rests below the sign in box. I believe you have already tried that solution where a link to create a new password is sent to your email ID. Let's find out what else we can do to fix Facebook account sign-in issue. 1. Use a Familiar Device


1 Answers

I have my profile fields set to the following

profileFields: ['email','id', 'first_name', 'gender', 'last_name', 'picture']

Even though you set email it might return emails if the user has multiple emails. So you need to check if email was returned profile.email or profile.emails[0].value. You must also check if it is undefined, because there is people that register with facebook that never verify their email account and there is people that sign up with a phone number, in both those cases their emails will always be undefined.

you want to check that any required fields have values.

var email = profile.email || profile.emails[0].value;
            if (! email){
              console.log('this user has no email in his FB');
              var err = {message:'this user is missing an email'};
              return done(err);
            }

now i can do this if they have an email

newUser.facebook.email = email;

if they don't have an email you can set a session for profile and send them to a page that asks them to enter an email.

It sounds like a pain, but you can never trust information from a third party api to have values.

Most of the passport examples I've seen online are wrong. They all assume an email is present.

like image 149
Richard Torcato Avatar answered Sep 21 '22 15:09

Richard Torcato