2

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
      // }
    };
  }
})();
Blowsie
  • 40,239
  • 15
  • 88
  • 108
  • 1
    Please consider to provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) if possible, or at least post what you have tried so far (code)/what you're trying to do (be more specific). This is too broad IMO – lealceldeiro Feb 28 '17 at 15:04
  • @AsielLealCeldeiro, in this case I would disagree. Its as per the demo https://cdn.rawgit.com/Narzerus/angular-permission/0d502cb4/test/e2e/permission-ui/assets/demo.html – Blowsie Feb 28 '17 at 15:11

1 Answers1

3

@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 */ });
    }
  },
};
Xavier Haniquaut
  • 1,003
  • 9
  • 22