Zend Navigation and RBAC

扶醉桌前 提交于 2019-12-01 00:37:21

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!