1

如何在 angularJS 的 Blur-Admin 模板中实现基于角色的访问控制?在哪里定义角色?涉及哪些文件?

4

1 回答 1

1

完美且有效的解决方案!该解决方案基本上提供了对该组件允许的角色的受限访问。

params以这种方式在所有主要模块中定义-(例如)-

(function() {
  'use strict';

  angular.module('BlurAdmin.pages.components', [
      'BlurAdmin.pages.components.mail',
      // 'BlurAdmin.pages.components.timeline',
      // 'BlurAdmin.pages.components.tree',
      // 'BlurAdmin.pages.components.fileUpload',
    ])
    .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider) {
    $stateProvider
      .state('main.components', {
        url: '/components',
        template: '<ui-view  autoscroll="true" autoscroll-body-top></ui-view>',
        abstract: true,
        title: 'Components',
        sidebarMeta: {
          icon: 'ion-gear-a',
          order: 100,
        },
        authenticate: true,
        params: {                // <-- focusing this one
          authRoles: ['admin']   // <-- roles allowed for this module
        }
      });
  }
})();

修改baSidebar.service.jsgetAuthorizedMenuItems ,在下面添加一个新函数getMenuItems(便于理解)。然后只需authRolesdefineMenuItemStates().

因此,getAuthorizedMenuItems()将包含以下代码 -

this.getAuthorizedMenuItems = function(user) {
    var states = defineMenuItemStates();
    var menuItems = states.filter(function(item) {
        return item.level == 0 && _.includes(item.authRoles, user.role);
    });

    menuItems.forEach(function(item) {
        var children = states.filter(function(child) {
            return child.level == 1 && child.name.indexOf(item.name) === 0;
        });
        item.subMenu = children.length ? children : null;
    });

    return menuItems.concat(staticMenuItems);
};

更新defineMenuItemStates()将是 -

function defineMenuItemStates() {
    return $state.get()
        .filter(function(s) {
            return s.sidebarMeta;
        })
        .map(function(s) {
            var meta = s.sidebarMeta;
            return {
                name: s.name,
                title: s.title,
                level: ((s.name.match(/\./g) || []).length - 1),
                order: meta.order,
                icon: meta.icon,
                stateRef: s.name,
                authRoles: s.params ? s.params.authRoles : undefined        // <-- added this
            };
        })
        .sort(function(a, b) {
            return (a.level - b.level) * 100 + a.order - b.order;
        });
}

现在,是时候使用BaSidebarCtrl.jsgetAuthorizedMenuItems中新添加的方法了。以这种方式使用它 -

// FYI, I got userCreds in BaSidebarCtrl as following -
var userCreds = localStorage.getObject('dataUser');
// note that getMenuItems is just replaced with getAuthorizedMenuItems(userCreds)
// $scope.menuItems = baSidebarService.getMenuItems();
$scope.menuItems = baSidebarService.getAuthorizedMenuItems(userCreds);

所以,你的user object会看起来像这样 -

var userCreds = {
    userName: 'test@mail.com',
    passWord: 'testpwd',
    role: 'admin'
};

而已!

于 2017-08-16T03:56:52.557 回答