Limit user access


#1

Hi!

I am creating an app with Ionic. I need that when the user is not logged, and he go to another state/page that it is not the log/register view, the app move it to the login or register.

but my code generates a loop.

$rootScope.$on('$stateChangeStart', function(event, toState, fromState){
    if(!UserFactory.isLoggedIn() && (toState.name !== 'login' ||  toState.name !== 'register'){
        event.preventDefault();
        $state.go('login');
    }
});

any solution?

thanks!

pd: Sorry for my poor English.


#2

Use UI router’s onEnter function on your state manager. It is a callback function that will be called whenever the state you declared it in is entered.

For whatever states you wish to check, I don’t have your code, but it could be something like this:

.state('yourState', {
        url: 
        views: {    
        },
        onEnter: function($state,UserFactory){
                UserFactory.isLoggedIn().then(function(isLoggedIn){
                   if(!isLoggedIn) $state.go('login');
                });
            }
    })

#3

thanks!

it works like a charm.

my apps now has a few views, but in a future, this would had many views more.

is there a general solution for that?

thanks a lot!


#4

Well, I personally like to sometimes customize my callback function depending on the state i’m in.

But if you wan’t a general approach, I believe your approach should be correct. I’m not really sure why it isn’t working. I couldn’t replicate in my code. If you could post an example somewhere it would be great

Does it happens no matter which state you transition to? Or only in some cases? Are you testing from your browser or from some other platform?