Search code examples
node.jspassport.jspassport-facebook

passport.authenticate('facebook') times out waiting for localhost


I am trying to implement facebook login into an existing express app using passport-js. Following the documentation this seems pretty forward - but now I have hit a spot where I don;t know what to do.

Basically once I access the route /auth/facebook in my browser, the browser times out waiting for the server. There are no errors in the console - all I can see is the log of the request. Placing a breakpoint on the passport function is no help as well.

So I really don't know what I can debug or try to change here.

This is my user model:

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let findOrCreate = require('mongoose-findorcreate');

// User schema definition
let UserSchema = new Schema(
    {
      provider: { type: String, required: true },
      id: { type: String, default: 'unknown' },
      disaplyName: { type: String, default: 'unknown' },
      name: { type: Object },
      emails: { type: Array },
      photos: { type: Array },
      createdAt: { type: Date, default: Date.now },
      updatedAt: { type: Date, default: Date.now },
    }
);

UserSchema.plugin(findOrCreate);

// Sets the updatedAt parameter equal to the current time
UserSchema.pre('save', (next) => {
  now = new Date();
  if(!this.updatedAt) {
    this.updatedAt = now;
  }
  next();
});

module.exports = mongoose.model('user', UserSchema);

facebook routes:

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

let User = require('../models/user');

passport.use(new FacebookStrategy({
    clientID: 123456,
    clientSecret: 'mysupersecretsecret',
    callbackURL: 'http://localhost:1337/auth/facebook/callback'
  },
  (accessToken, refreshToken, profile, done) => {
    User.findorCreate((err, user) => {
      if (err) {
        return done(err);
      }
      done(null, user);
    })
  }
));

function redirectFB() {
  passport.authenticate('facebook');
}

function callbackFB() {
  passport.authenticate('facebook'), {
    successRedirect: '/word',
    failureRedirect: '/'
  }
}

module.exports = { redirectFB, callbackFB };

server usage of those routes (I'm only adding the relevant parts of the server file here):

let facebook = require('./app/routes/facebook')

app.route('/auth/facebook')
    .get(facebook.redirectFB);

app.route('auth/facebook/callback')
    .get(facebook.callbackFB);

Can anyone spot what I am doing wrong?


Solution

  • The problem is how you define and use your facebook routes. Calls to passport.authenticate returns a request handler, but you don't pass it to app.route(...).get. You just don't use it at all.

    E.g. for redirectFB it should be:

    function redirectFB() {
      return passport.authenticate('facebook');
    }
    

    and

    app.route('/auth/facebook')
      .get(facebook.redirectFB());