Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passport-facebook: how to dynamically set callbackURL?

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 ?

like image 300
Gal Ben-Haim Avatar asked Jan 01 '13 15:01

Gal Ben-Haim


3 Answers

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

like image 71
Gal Ben-Haim Avatar answered Nov 09 '22 09:11

Gal Ben-Haim


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
like image 31
Andi Giga Avatar answered Nov 09 '22 09:11

Andi Giga


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.

like image 3
kateray Avatar answered Nov 09 '22 07:11

kateray