Tony Martinez
Tony Martinez

Reputation: 335

Node.js Passport Facebook Authentication no email returned

I'm trying to set up facebook authentication using passport from node.js. When I run the app and go to /auth/facebook, I go to a facebook page to give permission for facebook to return my email. But after I hit ok I get a page(the callback) that says "No emails associated with this account!" Which according to the code means that profile.emails is null. What am I missing?

These are the warnings that show up when I start the app. I don't know if they're the problem though.

express-session deprecated undefined resave option; provide resave option auth.js:44:37
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option auth.js:44:37

Here's the authorization code. I'm going through the intro MEAN stack course M101X from edx.

function setupAuth(User, app) {
  var passport = require('passport');
  var FacebookStrategy = require('passport-facebook').Strategy;

  // High level serialize/de-serialize configuration for passport
  passport.serializeUser(function(user, done) {
    done(null, user._id);
  });

  passport.deserializeUser(function(id, done) {
    User.
      findOne({ _id : id }).
      exec(done);
  });

  // Facebook-specific
  passport.use(new FacebookStrategy(
    {
      clientID: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
      callbackURL: 'http://localhost:3000/auth/facebook/callback'
    },
    function(accessToken, refreshToken, profile, done) {
      if (!profile.emails || !profile.emails.length) {
        return done('No emails associated with this account!');
      }

      User.findOneAndUpdate(
        { 'data.oauth': profile.id },
        {
          $set: {
            'profile.username': profile.emails[0].value,
            'profile.picture': 'http://graph.facebook.com/' +
              profile.id.toString() + '/picture?type=large'
          }
        },
        { 'new': true, upsert: true, runValidators: true },
        function(error, user) {
          done(error, user);
        });
    }));

  // Express middlewares
  app.use(require('express-session')({
    secret: 'this is a secret'
  }));
  app.use(passport.initialize());
  app.use(passport.session());

  // Express routes for auth
  app.get('/auth/facebook',
    passport.authenticate('facebook', { scope: ['email'] }));

  app.get('/auth/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/fail' }),
    function(req, res) {
      res.send('Welcome, ' + req.user.profile.username);
    });
}

module.exports = setupAuth;

Upvotes: 1

Views: 212

Answers (1)

Treefish Zhang
Treefish Zhang

Reputation: 1161

Did you try adding profileFields inside the passport.use block like suggested in that course's Discussion Tab, under "Facebook Authentication Problem"?

Upvotes: 1

Related Questions