0

I'm using Google auth through Passport in my app and I'm attempting to redirect the user back to the original page they requested after successful sign-in. I think that location.reload() may be the problem, but not sure how to solve it.

routes.js:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
  res.redirect(req.session.returnTo);
  req.session.returnTo = null;
});

middleware.js:

var isAuth = function(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  } else {
    req.session.returnTo = req.url;
    return res.redirect('/');
  }
};

called on button click:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    location.reload();
});
MattDionis
  • 3,534
  • 10
  • 51
  • 105

1 Answers1

3

Try:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
   var backURL = req.header('Referer') || '/';
   res.json({redir: backURL});
});

And:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    window.location.href = data.redir;
});
michelem
  • 14,430
  • 5
  • 50
  • 66
  • When I look in the console that seems to have worked, as the correct page was loaded behind the scenes. Yet the actual page never updates. Strange. – MattDionis Jun 18 '15 at 17:26
  • thanks but unfortunately that results in 'Cannot GET /undefined'. – MattDionis Jun 18 '15 at 17:39
  • What's interesting is that when I `console.log(data)` in place of `window.location.href = data.redir` I see all the HTML of the page I was hoping to see. Could this be because I'm using Jade to serve my HTML files? – MattDionis Jun 18 '15 at 17:44
  • did you change the Node part too with this `res.json({redir: backURL});`? – michelem Jun 18 '15 at 17:50
  • the idea is to send the url string in json to the post response and use that to window.location.href – michelem Jun 18 '15 at 17:51