0

I have an angular app. Every route has a required user group value. The field is required.

.state('dogQuery', {
    url:'/dog',
    templateUrl: templatePath + '_DogQuery.html',
    controller: 'DogQueryCtrl',
    controllerAs: 'vm',
    requireADLogin: true,
    group: 'Admin'
})

Or, for generic pages that should be public to everyone:

.state('403', {
    url: '/403',
    templateUrl: templatePath + '_403.html',
    controller: 'DashboardCtrl',
    controllerAs: 'vm',
    group: 'None'
});

So far, this is my best guess on how to actually enforce the groups:

$rootScope.$on(
    '$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams){
        event.preventDefault();

        if(toState.group === 'Admin') {
            user.isAdmin().then(function (response) {
                if (response === true) {
                    $urlRouter.sync();
                }
                else {
                    $state.go("403")
                }
            });
        }
        else if(toState.group === 'None'){
            $urlRouter.sync();
        }
        else {
            $state.go("403");
        }
    }
);

The idea being execution pauses on each request while the user's group is checked. If they are in the right group, take them where they wanted to go, via $urlRouter.sync(). If the user is not in the right group, take them to a 403 page via $state.go().

Unfortunately, the code as written results in a loop. If the user is not an admin, they are sent to the 403 route via $state.go(). The 403 page triggers the same group check, but since it's group requirement is "None" then $urlRouter.sync() is triggered. At this point, I was assuming that would take us to the 403, but no, $urlRouter.sync() loads the old /dog route, which triggers the 403 reroute again, and I'm stuck in a loop.

To rephrase, is there a way to get $urlRouter.sync() to update to whatever $state.go() sets the current page to? Should I be using something other than $state.go() in this situation?

Thanks!

crowhill
  • 2,398
  • 3
  • 26
  • 55
  • 1
    Have you tried using `resolve`: https://github.com/angular-ui/ui-router/wiki#resolve . You'll then be able to check for your user before your controller is instantiated – t3__rry Sep 26 '16 at 19:43
  • Check [this answer](http://stackoverflow.com/a/29797145/5297399) . I used this in my project and worked well so far. It uses resolve too as @t3__rry said above. – Gabriel Hobold Sep 26 '16 at 19:48

0 Answers0