How to implement Role Based Access Control in Blur-Admin template for angularJS? Where to define roles? Which files are concerned?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Perfect and Working Solution! This solution basically provides restricted access to the roles allowed for that component.
define
params
in all of your main modules in this way - (for example) -
(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
}
});
}
})();
Modify baSidebar.service.js, add a new function
getAuthorizedMenuItems
just belowgetMenuItems
(for easy understanding). And then just add a single parameterauthRoles
indefineMenuItemStates()
.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);
};
And updated
defineMenuItemStates()
will be -
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;
});
}
Now, it's time to use the newly added method
getAuthorizedMenuItems
in BaSidebarCtrl.js. Use it this way -
// 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);
So, your
user object
will look something like this -
var userCreds = {
userName: 'test@mail.com',
passWord: 'testpwd',
role: 'admin'
};
That's it!