17
votes

I'm following this example to setup a FacebookStrategy - https://github.com/jaredhanson/passport-facebook/blob/master/examples/login/app.js

I want to set the callbackURL dynamically, ie: the user access /posts/34 so the callback will be /posts/34/callback

how can I achieve something like this ?

4

4 Answers

10
votes

I found the solution, both the auth redirect route and the callback route should wrap passport.authenticate() with function(req, res, next).

I followed the example in http://passportjs.org/guide/authenticate/ for custom callback

and the comments in https://github.com/jaredhanson/passport-facebook/issues/2 for custom callbackURL

10
votes

I use this solution, It is quite easy. I save the last url in the session and collect it afterwards. If you pass the callback url to fb directly you need to permit all the different routes which is quite a hazzle.

  app.get '/auth/facebook/', routesService.clean, (req, res, next) ->
    req.session.redirect = req.query.redirect if req.session? && req.query.redirect?
    passport.authenticate('facebook', { scope: ['user_friends'] }) req, res, next
    return

  app.get '/auth/facebook/callback', passport.authenticate('facebook', failureRedirect: '/login'), (req, res) ->
        # Successful authentication, redirect home.
        if req.session?.redirect?
          rediredUrl = req.session.redirect
          delete req.session.redirect
          res.redirect '/#!'+ rediredUrl
        else
          res.redirect '/'
        return
3
votes

Just following up on Gal's answer, here's that combined solution:

app.get('/auth/facebook', (req, res, next) => {
  passport.authenticate('facebook')(req, res, next)
})

app.get("/auth/facebook/callback", (req, res, next) => {
  passport.authenticate('facebook', (err, user, info) => {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login')}
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.uid)
    });
  })(req, res, next)
})

Note that you have to specifically log the user in.

0
votes

with passport js you can just set successReturnToOrRedirect

router.get('/facebook/callback', (req, res, next) =>
    passport.authenticate('facebook', {
        callbackURL: `https://${req.get('host')}/api/auth/facebook/callback`,
        successReturnToOrRedirect: req.session.redirect || '/',
        failureRedirect: '/',
        successRedirect: '/',
    })(req, res, next)
);