Sergey Goliney Sergey Goliney - 4 months ago 24
AngularJS Question

Check if user has permission to access specific states

I use angular-permission and I want to check if user has access to specific states.

My state config:

$stateProvider
.state('app', {
url: '/',
abstract: true,
data: {
permissions: {
only: ['BASE']
}
}
})


Is there a method or something which I can use in controllers to determine it?

// somewhere in controller
if (Permission.hasAccessToState('app')) {
// I want to check if user has access to state without navigating to it
};





If anyone is interested, here is a corresponding discussion on github.

Answer

I did not find something in the documentation wiki. But according to the source and comment there seems to be an Authorization Service available which u can take advantage of.

//inject PermissionMap and Authorization    
App.controller('Controller',function(PermissionMap,Authorization,$scope) {

     //get the state by name an assign it to `state`
      var permissionMap = new PermissionMap(state.data.permissions);

      var authorizationResult = Authorization.authorize(permissionMap);

      authorizationResult
        .then(function () {
          //authorized
        })
        .catch(function (rejectedPermission) {
          //unauthorized
        });
});

Check out this code and see if it works

UPDATE

After ur reply, i looked deeper into the code. Maybe we need StatePermissionMap and StateAuthorization instead.

 var statePermissionMap = new StatePermissionMap(state);

  StateAuthorization
      .authorize(statePermissionMap)
      .then(function () {
         //authorized
      })
      .catch(function (rejectedPermission) {
        //unauthorized
      })
Comments