简体   繁体   中英

Angular/Express: Redirecting to the last page visited after logging in

A similar-ish question here (but not applicable).

In my SPA I'm using PassportJS to handle authentication. I have many routes which require the user to be logged in. I route like this:

// ... other routing stuff
when('/insights', {
    templateUrl: 'partials/insights',
    controller: 'insightsCtrl',
    resolve: { 
        loggedin: checkLoggedin 
    }
})

var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){ 
  var deferred = $q.defer(); 
  $http.get('/loggedin').success(function(user){ 
    if (user !== '0') {
        $rootScope.user = user;
        deferred.resolve(); 
    }
    else { 
      deferred.reject(); 
      $location.url('/login'); 
    } 
  }); 
return deferred.promise; 
};

My route to check if logged in:

app.get('/loggedin', function(req, res) {
    res.send(req.isAuthenticated() ? req.user : '0');
});

If they're not logged in, they're redirected to /login . Once that is successfully done though, I'd like to go back to the original page they tried to request.

Is there a built-in way to store the route the user is trying to access so that I can redirect to it once they're logged in? I can do this with a cookie I suppose, but it feels a little clunky to do so...

There is no built in approach besides using the custom callback that PassportJS provides , but if you are writing this for a SPA, you could leverage $cacheFactory and create a service/factory that stores the last visit page of that user.

Limitations for $cacheFactory are the same as local storage which are that they are domain specific, so if you change domains, your local storage will not be the same cross-domain.

You can use a custom callback as explained in passportjs documentation . With custom callback, you can send the current query string to your server, and get a redirect to same query string after successful login.

Another possibility is to use localStorage to save current state and take it after login. You have many modules to use localStorage with angular like angular-local-storage .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM