How can I return to the current hash location using Passport.js?

I use Passport.js to authenticate with Google through OAuth (I use the passport-google-oauth strategy). It works fine, but I am currently redirecting the user to "/" and I would like to send them to "/" plus the current hash tag. I can send the hash value to the query string parameter, but I cannot show this value for the callbackURL property of the object that I pass for authentication.

Can someone give an example or explanation on the right way to do this? I don't have to use a query string, it's just the easiest way, but I'm open to using a session variable or something else if it is easier or better.

Thank.

+5
source share
1 answer

You can achieve this effect by storing the returned url in the session.

// server
var app, express;

express = require('express');

app = express();

app.configure(function() {
  app.use(express.cookieSession({secret: 'shh'}));
});

app.get('/auth/twitter', function(req, res, next) {
  // to return to '/#/returnHash', request this url:
  // http://example.com/auth/twitter?return_url=%2F%23%2FreturnHash

  // on the client you can get the hash value like this:
  // encodeURIComponent("/"+window.location.hash)
  req.session.return_url = req.query.return_url;
  next();
}, passport.authenticate('twitter'));

app.get('/auth/twitter/callback', passport.authenticate('twitter', {
  failureRedirect: '/login'
}), function(req, res) {
  var url = req.session.return_url;
  delete req.session.return_url;

  // redirects to /#/returnHash
  res.redirect(url);
});
+3
source

All Articles