Search code examples
javascriptnode.jspassport.jspassport-facebook

Node.js passport-facebook callback looping


I'm using passport-facebook to login my users and i´m getting into undefined loop when facebook calls myt callback. I have read lot of sites and question, even here, but really, i cant find any solution.

Here is the code, I´m going to put it all here, like it were into une single file:

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

var server = restify.createServer();
server.use(restify.bodyParser());

passport.use(new FacebookStrategy({
  clientID: 'APP_ID',
  clientSecret: 'APP_SECRET',
  callbackURL: 'http://192.168.0.13:8080/login/facebook/callback'
  }, function (token, refreshToken, profile, done) {
        //this code never is executed, why?
        return done(null, profile);
  }));

server.use(passport.initialize());

server.get('/login/facebook', function(req, res, next) {
    passport.authenticate('facebook', { display: null, scope: ['email']})(req, res, next);
});

server.get('/login/facebook/callback', (req, res, next) => {
        //here is where the loop happends, i´m getting into this and never can go out from here
        passport.authenticate('facebook', function(profile) {
            //I could not execute this
            if (!profile || !profile.id) {
                return res.json(500, 'We had trouble signing you up with Facebook. Please try again or sign-up via email.');
            } else {
                res.json(200, profile);
            }
        })(req, res, next);
});

server.listen(config.port, function () {
  console.log('%s listening at %s', server.name, server.url);
});

Really, i'm very frustrated, i now, i now, there are thousands of post talking about that... I tried all of them, i'm here anyway...

Thanks.


Solution

  • I found the problem after a little while. What i've posted was the result of multiple test.

    The problem was i was using in a bad way the parhentesis. Being simplest, I was doing this:

    server.get('/login/facebook/callback', passport.authenticate('facebook', (req, res, next) => { /* magic here*/ });
    

    So, the callback for next() execution was passed like it was into the authenticate method. This was not because I didn't understand the problem, It was just I didn't realize where the error was.

    The correct way should be:

    server.get('/login/facebook/callback', passport.authenticate('facebook'), (req, res, next) => { /* magic here */ });
    

    Thanks everybody for cooperating.