3

Currently I'm implementing ng-token-auth into my Angular application, while this works great, I'm having some trouble with restricting access to certain pages.

In some of my routes I have a couple of extra parameters:

data: {
    title: 'Dashboard',
    restricted: true, // Only allow logged in users
    role: 2 // Only allow a specific role
}

I'm doing this checking login in $stateChangeStart, so before I switch routes, I can check if the user is allowed to that route.

I followed the ng-token-auth suggestions about using a parent route with a resolve to check if a user is logged in or not:

resolve: {
    auth: function($auth) {
        console.log('validate user');

        return $auth.validateUser();
    }
}

Now the problem comes when I first load up the application, obviously the $stateChangeStart event is fired before the $auth.validateUser() has been resolved, because of that the login inside the $stateChangeStart fails and the user is redirected to the login page.

What would be the better way of implementing this "permissions logic", I don't want to do it per route, as that would add in a lot of extra work and code.

Doing it in the $stateChangeStart also doesn't seem to be the best options as that doesn't work on first load.

woutr_be
  • 9,532
  • 24
  • 79
  • 129
  • Why can't you check `auth` in `$stateChangeSuccess`? `$stateChangeSuccess` would only be fired, AFAIK, when all `resolve` promises are resolved, including `auth`. – New Dev Dec 09 '14 at 02:32
  • @NewDev I could do that, but other routes have more `resolve` promises, I'm not sure if I should be making the user load extra data for something he can't access. – woutr_be Dec 09 '14 at 02:51
  • 1
    Actually, forget about `$stateChangeSuccess`. Take a look at this [SO answer](http://stackoverflow.com/a/22540482/968155) instead – New Dev Dec 09 '14 at 05:29
  • @NewDev That link helped me a lot, thanks for that! I used the example that they provided and implemented it into my own application and it seems to do what I want. – woutr_be Dec 12 '14 at 01:47

1 Answers1

1

I would treat Authentication and Authorization as two different things.

ng-token-auth helps you with Authentication. It even helps you with selecting which routes must be available for authenticated users Refer to example-using-angular-ui-router

role: 2 // Only allow a specific role

seems more of authorization and permissions. For that you may want to take a different approach. One such approach. We took a similar approach - we also made sure some of the authorization was fetched upfront.

Ryan Leaf
  • 1,025
  • 8
  • 7
bhantol
  • 9,368
  • 7
  • 44
  • 81