3

I have one main controller for my app - AppCtrl and use ui-router. How can I make secured states?

$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
    var authorization = toState.data.authorization;

    if(!Security.isAuthenticated() && authorization != false)
        $location.path('/login');
});

For example I want to make books and authors states secured, and login state not secured.

.state('login', {
                url: '/login',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: false
                }
            })
.state('books', {
                url: '/books',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: true
                }
            })
.state('authors', {
                url: '/authors',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: true
                }
            })

Security.isAuthenticated() function returns boolean. When I open /books everything works perfectly, page are being redirected to /login, when after redirecting I open /authors, page loads and it's content are shown, but browser's url is /login, so page being redirected, but somehow it's content are shown.

user3215609
  • 535
  • 2
  • 8
  • 19

1 Answers1

3

Figured out that I have to prevent opening next route, and go to login state. Made some changes and all works perfectly.

if (!Security.isAuthenticated() && authorization != false){
        event.preventDefault();
        $state.go('login');
    }
user3215609
  • 535
  • 2
  • 8
  • 19
  • Looks neat. May I ask where you put the if (!Security.isAuthenticated()... block ? – Stephane Sep 12 '14 at 15:11
  • Sorry. Just saw now you have it with the rootScope state change handler. – Stephane Sep 12 '14 at 15:12
  • I still wonder how to have it in my multiple modules application. In my case I need to have my rootScope in a module utilsModule.run( or in the app.run(. But then no way to reference the $state.current.data.securedRoute route data. – Stephane Sep 12 '14 at 15:31
  • I would also be interested in alternatives to the `.run()` method. – Stephan Kristyn Sep 25 '14 at 14:08