angular-permission: Testing a user has a role or permission from a controller

996 Views Asked by At

I have defined my user roles and permissions in my application as per the documentation.

https://github.com/Narzerus/angular-permission/wiki

With this I am able to use the ui directives or ui-router handling.


Q: How to test that a user has a role or permission within a controller or service?

(function() {
  'use strict';

  angular
    .module('app')
    .component('userDetail', component());

  /** @ngInject */
  function component() {
    return {
      restrict: 'E',
      bindings: {
        user: '<'
      },
      templateUrl: 'app/components/users/user-detail/user-detail.html',
      transclude: true,
      controller: Controller
    }
  }

  /** @ngInject */
  function Controller($log) {
    var ctrl = this;
    ctrl.$onInit = function() {
      $log.log('How to test for user permission?')
      // Something like...
      // if(PermPermission.hasPermission('createUser')) {
      // do something
      // }
    };
  }
})();
1

There are 1 best solutions below

0
On

@blowsie this is how I managed it, but it feels very heavy:

export default {
  template: '<div></div>',
  controller: class test {
    /* @ngInject */
    constructor(PermPermissionStore) {
      PermPermissionStore.definePermission('truePermission', () => true);
      PermPermissionStore.definePermission('falsePermission', () => false);

      const truePerm = PermPermissionStore.getPermissionDefinition('truePermission');
      const falsePerm = PermPermissionStore.getPermissionDefinition('falsePermission');

      truePerm.validatePermission()
        .then((res) => { /* you go there */ })
        .catch((e) => { /* never go there */ });
      falsePerm.validatePermission()
        .then((res) => { /* never go there */ })
        .catch((e) => { /* you go there */ });
    }
  },
};