AngularJs Directive role-based display of sections

Display controls based on isOwner and user role.

by Tapan Acharjee

HTML

<div ng-app="demoApp" ng-controller="mainController as ctrl">
  current user object:
  <pre>{{ctrl.user | json : 2}}</pre>
  <ul>
    <li ng-repeat="msg in ctrl.messages">
      {{msg.text}}
      <div access rights="ctrl.user.uid === msg.uid" role="ctrl.user.role" req-roles="{{['admin']}}">
        <h2>controls that are only visible for owner or admin</h2>
        <div ng-show="auth.role">
          <!-- auth = current authorisation of user -->
          user has role = {{auth.role}}
        </div>
        <div ng-if="auth.isAdmin">
          user is admin
        </div>
        <div ng-if="auth.hasRights">
          has owner rights
        </div>
        other roles:<br/>
        isMod: {{auth.isMod}}<br/>
        isUser: {{auth.isUser}}
      </div>
    </li>
  </ul>
</div>

JavaScript

angular.module('demoApp', [])
  .controller('mainController', MainController)
  .directive('access', AccessDirective);


function MainController() {
  var vm = this;
  angular.extend(vm, {
    hello: 'hello from angular',
    user: {
      uid: 123,
      role: 'user' //'admin'
    },
    messages: [{
      uid: 123,
      text: 'hello from 123'
    }, {
      uid: 234,
      text: 'hello from 234'
    }, {
      uid: 123,
      text: 'another hello from 123'
    }]
  });
}

// working, second message control should be hidden for user with uid 123 and user role
// read more about scope binding here:
// http://stackoverflow.com/questions/31344668/inject-object-into-scope-of-transcluded-content-in-angular-1-3
function AccessDirective($compile) {
  //var template = '<div ng-if="accessCtrl.rights || accessCtrl.checkRole()"></div>';
  var availableRoles = ['admin', 'mod', 'user'],
  		defaultBindingName = 'auth',
      debugFirebaseRules = false; // if a malicious user has found a way to show the controls with this set to true you can test your firebase rules --> remove this in production!!
  
  return {
    transclude: true,
    //replace: true,
    scope: {},
    bindToController: {
      rights: '=',
      role: '=',
      availRoles: '@?', // passing a list of avaliable roles e.g. admin, moderator to create isAdmin, isModerator properties --> default roles are admin, mod, user
      reqRoles: '@' // if user has this role he can also see the controls --> e.g. admin
    },
    controllerAs: 'accessCtrl',
    controller: function($scope) {
      var vm = this;
			vm.availRoles = angular.extend(availableRoles, 		
      	$scope.$eval(vm.availRoles));//.split(',');
      vm.bountItemName = vm.boundItemName || defaultBindingName;
      
      vm.reqRoles = $scope.$eval(vm.reqRoles);
      
      /*if ( vm.reqRoles && angular.isString(vm.reqRoles) ) {
      	vm.reqRoles = vm.reqRoles.split(',');
      }*/
      	
      //console.log(vm.reqRoles);
      vm.checkRole =...