Reputation: 225
I am developing a ZF2 based site. I have a main navigation which stays same regardless of the visitor/user status. Need to add another component/nav, which will depend on the user's status and role. For a visitor the items will be
For a logged-in normal user, it will display
And for some users with specific roles/permission there will be additional items
I want to use RBAC, as ACL seems bloated, and also just to check if the current logged in user/role has additional items, I need to load the complete ACL (and we got around 15+ different types of roles).
I spent some time thinking how I have achieve this, so following are some ideas I have.
PS: I need to use a partial as I need to add some CSS class to the language selection section. Also the navigation will be displayed in the layout.
Upvotes: 2
Views: 2255
Reputation: 1688
I am using ZfcRbac and I am doing it as the following, you can display the navigation based on user roles and the navigation items permission as the following:
First add a permission to your navigation item as the following:
'permission' => 'edit-profile',
Then attach a listener in the onBootstrap
as the following:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->getSharedManager()->attach(
'Zend\View\Helper\Navigation\AbstractHelper',
'isAllowed',
array('\Application\Listener\RbacListener', 'accept')
);
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
Then create a class Application\Listener\RbacListener
as the following:
public function accept(Event $event) {
$event->stopPropagation();
$accepted = true;
$serviceLocator = $event->getTarget()->getServiceLocator()->getServiceLocator();
$rbac = $serviceLocator->get('ZfcRbac\Service\Rbac');
$params = $event->getParams();
$page = $params['page'];
$permission = $page->getPermission();
if ($permission) {
$accepted = $rbac->isGranted($permission);
}
return $accepted;
}
and by this when you display the menu it will be filtered based on the permission and roles, for example if you do echo $this->navigation('navigation')->menu()
then only the menu items that the user has permission on will be displayed.
Upvotes: 3