How do I find original request path before redirec

2019-05-26 07:23发布

问题:

Let's say I am trying to access the path http://localhost:3000/users#/WyCrYc28r/foo/1414585518343. But the path /users needs to be accessed only by the authenticated users as following:

  app.get('/users', isLoggedIn, function (req, res) {
      req.session.user = req.user;
      res.cookie('uid', req.session.passport.user)
          .render('users', { title: 'The Foo Machine', user: req.user });
  });

And following is the isLoggedIn middleware:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
      return next();
  res.redirect('/login');
}

And following is how the login is being handled:

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/users', 
    failureRedirect: '/login', 
    failureFlash: true 
}));

I get redirected to the http://localhost:3000/users after logging in, but I want to the user to go to http://localhost:3000/users#/WyCrYc28r/foo/1414585518343 after successfully logging in as that was where the user wanted to go in the place place.

I am using PassportJS module for authentication/authorization here and have the front end developed in AngularJS.

Could somebody help me with it?

回答1:

I can think of two common solutions to this pattern. Adding the angularjs in there may complicate things a little, but maybe this will get you started:

1) save the url as a query param in the redirect url

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/login?fromUrl='+req.originalUrl);
}

then after login you get that value and do the redirect, something like:

app.post('/login', passport.authenticate('local-login'), { failureRedirect: '/login', failureFlash: true },
  function(req, res) {
    res.redirect(req.param('fromUrl'));
});

2) (Not as easy or scalable) use your session state to store the from-url. it might look like:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  req.session.fromUrl = req.originalUrl;
  res.redirect('/login');
}

then after login you get that value and do the redirect, something like:

app.post('/login', passport.authenticate('local-login'), { failureRedirect: '/login', failureFlash: true },
  function(req, res) {
    res.redirect(req.session.fromUrl);
});