Reputation: 6098
I am having an app that every page except login requires authentication. I do this by checking the $stateChangeStart and then redirecting to /login when token is not set. on initial app load this works fine, but at login screen if i type another "restricted" url. It does the check, changes the url, but still loads the restricted page. What am I missing here?
//app.run:
app.lazy = $couchPotato;
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$on('$stateChangeStart', function(event, toState, toStateParams) {
console.log("state changed to "+toState.name);
console.log(toState);
Authentication.validateLogin(toState, toStateParams);
});
Authentication.validateLogin:
validateLogin:function(toState, toStateParams){
$rootScope.toState = toState;
$rootScope.toStateParams = toStateParams;
if ($localStorage.token == null) {
console.error("Not Authenticated!");
$location.url('/login');
}
}
Upvotes: 0
Views: 190
Reputation: 1147
I see that your using angular-ui, so I'm not exactly sure what advantages that has over using 'basic' angular, but I wrote this to handle validating a token when the route changes.
app.run(['$rootScope', 'authService',
function ($rootScope, authService) {
$rootScope.$on("$routeChangeSuccess", function (event, next, current) {
if (next && next.$$route && authService.isAuthenticated()) {
authService.validate();
$rootScope.appTitle = next.$$route.title;
}
});
}]);
The $routeChangeSuccess handles navigation to routes after the controller has loaded (very important for objects that load when the page loads when validation is confirmed), and then validates them.
This also performs 2 checks in that it checks if the token in local storage exists and is formed correctly, and if it is, send it back to the server to confirm that.
I also found that I had to use the $locationChangeStart to handle page refresh, to re-validate when someone tries to refresh the page.
The validateLogin solution:
validateLogin:function(toState, toStateParams){
if(toState.access){
if(toState.access.loginRequired){
if ($localStorage.token == null) {
$state.go('login');
}
}
}
Upvotes: 1
Reputation: 6098
Try this with the validateLogin:
validateLogin:function(toState, toStateParams){
if(toState.access){
if(toState.access.loginRequired){
if ($localStorage.token == null) {
$state.go('login');
}
}
}
}
Upvotes: 0