getAuthorizedMenuItems

getAuthorizedMenuItems

本文介绍了AngularJS Blur-Admin模板中基于角色的访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐答案

在所有 主模块 中定义 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
        }
      });
  }
})();

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

So, getAuthorizedMenuItems() will contain following code -

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);
};
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;
        });
}
// 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);
var userCreds = {
    userName: '[email protected]',
    passWord: 'testpwd',
    role: 'admin'
};

这篇关于AngularJS Blur-Admin模板中基于角色的访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 20:54