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.

1

1 Answer 1

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');
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Looks neat. May I ask where you put the if (!Security.isAuthenticated()... block ?
Sorry. Just saw now you have it with the rootScope state change handler.
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.
I would also be interested in alternatives to the .run() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.