I recently asked a more complex question on Stack Overflow regarding AngularJS logout action. However, I have another aspect that I believe warrants a separate question.
In my Angular SPA, I have implemented authentication using bearer JWT tokens. I utilize ng-route to navigate between different views. For example, one view (/protected route, protectedController and protectedDataService) contains protected resources, while another view (/unprotected route, unprotectedController and unprotectedDataService) contains unprotected resources. Below are sample code snippets for the controllers:
(function () {
'use strict';
angular
.module('protectedCtrl',[])
.controller('protectedController', ['$location','protectedDataService', function ($location, protectedDataService) {
var vm = this;
vm.title = 'protectedController';
protectedDataService.getData().then(function (res) {
vm.values = res.data;
}, function (err) {
console.log(err);
});
}]);
})();
Unprotected controller:
(function () {
'use strict';
angular
.module('unprotectedCtrl',[])
.controller('unprotectedController', ['$location','unprotectedDataService', function ($location, unprotectedDataService) {
var vm = this;
vm.title = 'unprotectedController';
unprotectedDataService.getData().then(function (res) {
vm.values = res.data;
}, function (err) {
console.log(err);
});
}]);
})();
If an unauthenticated user tries to access a protected resource (/protected path), they will be redirected to the login page. However, in the scenario where a logged-in user clicks the logout button (for now manually deleting token info from local storage and reloading the page), how can I handle the redirection based on the active page? Specifically, if the user is on the /protected page, they should be redirected to the login page. If they are on the /unprotected page, no action should be taken. How can I determine which page is active in ng-view (requires auth or not) and make a decision about redirection?