A free and open-source book on ZF3 for beginners


17.15. Using the User Module

Congratulations, now our Role Demo is ready, so we make some resume of how you typically use it if you plan to base your own website on it.

First of all, you need to create all needed roles and permissions through the convenient user interface that we created. Assign a role (or several roles) to each website user.

Then edit the module.config.php configuration configuration file in your module and add two keys:

An example of that key is presented below:

// This key stores configuration for RBAC manager.
'rbac_manager' => [
    'assertions' => [Service\RbacAssertionManager::class],
],
'access_filter' => [
    'options' => [
        'mode' => 'restrictive'
    ],
    'controllers' => [
        Controller\IndexController::class => [
            // Allow anyone to visit "index" and "about" actions
            ['actions' => ['index', 'about'], 'allow' => '*'],
            // Allow authorized users to visit "settings" action
            ['actions' => ['settings'], 'allow' => '@']
        ],
    ]
],

The * and @ in the allow subkeys are not the only options. You can make the allow subkeys to look as follows. We allow access to the page to:

If your website has some dynamic assertions, extend the assert() method of the existing RbacAssertionManager class (or write and register your own assertion manager):

public function assert(Rbac $rbac, $permission, $params)
{
    $currentUser = $this->entityManager->getRepository(User::class)
            ->findOneByEmail($this->authService->getIdentity());
    
    if ($permission=='post.own.edit' && $params['post']->getUser()->getId()==$currentUser->getId())
        return true;
        
    if ($permission=='post.own.publish' && $params['post']->getUser()->getId()==$currentUser->getId())
        return true;        
    
    return false;
}

If you want to check permissions in a controller action, you can use the Access controller plugin as follows:

if (!$this->access('profile.own.view', ['user'=>$user])) {
    return $this->redirect()->toRoute('not-authorized');
}        

If you want to check permissions in a view template, you can use the Access view helper:

if ($this->access('profile.own.view', ['user'=>$user))) {
   // do something...
}

That's all! That simple! Enjoy!


Top