1

I have this code:

app.run(function($rootScope, $location, $window, AuthenticationService) {
        $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
            //redirect only if both isAuthenticated is false and no token is set
            if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication 
                && !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {

                $location.path("/admin/login");
            }
        });
    });

I get it that we have these ui-router methods: $stateChangeStart, $stateChangeSuccess, $stateChangeError, but how about nextRoute or currentRoute ?

Besides is there a way of achieving above without making use of the .run() block?

For reference: https://raw.githubusercontent.com/kdelemme/blogjs/master/app/js/app.js

Possible duplicate: AngularJS: ui-router secured states

Community
  • 1
  • 1
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147

1 Answers1

2

This works:

app.run(function($rootScope, $location, $window, AuthenticationService) {
    $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){

        if (!AuthenticationService.isAuthenticated && toState.access.requiredAuthentication != false){
            console.debug("NO AUTH");
            event.preventDefault();
            $state.go('login');
        }
    });
});
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147