简体   繁体   中英

AngularJs and Angular-UI-Router routes permissions

I'm facing an issue on how to implement route restrictions based on remote data gotten from the server.

Suppose I have the following config file:

angular.module('myApp')
  .config(['$stateProvider', function($stateProvider) {

    $stateProvider
      .state('post', {
        url: '/post/:post_id',
        abstract: true,
        [...]
    })
      .state('post.view', {
        url: '/view'
        [...]
    })
      .state('post.edit', {
        url: '/edit'
        [...]
    })

}]);

The requirements for my application are:

  • A post has an owner (creator of the post) and its domain may be public or private.

  • If the domain is public, every user will be able to see the post (entering state post.view ), and, if not (domain is private), only the owner will be able to see it.

  • The post.edit state is only accessible to the owner.

To do this, what is the best approach?

I was thinking of having a resolve promise that fetches the data from the server (post's domain and correspondent user role), performs the required checks and returns accordingly (promise resolved or rejected).

But then, how would I redirect the user to a correct state if he is not authorized? For example, a common user trying to access the post.edit state should be redirected to the post.view state, if the post's domain is public... But if the post's domain is private, an unauthorized access page should be presented. Is it a good approach to do this directly on the resolve? What are the alternatives?

Have a look at this great tutorial on routing authorization based on roles:

role based authorization

Also have a look at this stackoverflow answer, here there is conditional routing based on login, you can use the same logic of roles for your purpose,

Ui-router, routes based on permission

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM