zend-framework2zfcuserzfc-rbac

Second ZfcRbac Assertion is not working | ZF2


I have added below code inside zfc_rbac.global.php:

return [
'zfc_rbac' => [
   'assertion_map' => [
        'isAuthorizedToAddUser' => 'Application\Assertions\WhoCanAddUser',
        'isBranchOrOrgIdPresentIfNotAdmin' => 'Application\Assertions\BranchOrOrgIdPresentIfNotAdmin'
    ]
]]

And used it inside controller like below:

if (! $this->authorizationService->isGranted('isBranchOrOrgIdPresentIfNotAdmin')) {
    throw new UnauthorizedException('You are not authorized to add this aaa!');
}

but its throwing the exception even if I return true from assert method. But if I replace isBranchOrOrgIdPresentIfNotAdmin with isAuthorizedToAddUser, its working fine. What could be wrong here. Second assertion class BranchOrOrgIdPresentIfNotAdmin is just the replica of WhoCanAddUser class. Below is my WhoCanAddUser assertion class.

namespace Application\Assertions;

use ZfcRbac\Assertion\AssertionInterface;
use ZfcRbac\Service\AuthorizationService;
use ZfcRbac\Exception\UnauthorizedException;
use Zend\Session\Container;

class WhoCanAddUser implements AssertionInterface
{
    protected $notAuthorizedMessage = 'You are not authorized to add this user!';

    public function __construct()
    {
        $this->org_session = new Container('org');
    }

    /**
     * Check if this assertion is true
     *
     * @param AuthorizationService $authorization            
     * @param mixed $role            
     *
     * @return bool
     */
    public function assert(AuthorizationService $authorization, $role = null)
    {
        return true; //added this for testing if true is working and it worked, but second assertion is not working!
        switch($authorization->getIdentity()->getRole()->getName()){
            case 'admin':
                return true;
            break;
            case 'owner':
               if($role != 'member'){
                   throw new UnauthorizedException($this->notAuthorizedMessage);
               }
               return true;
            break;
            default:
                throw new UnauthorizedException($this->notAuthorizedMessage);
            break;
        }

        if($authorization->getIdentity()->getRole()->getName() != 'admin' && !$this->org_session->offsetExists('branchId')){
            throw new \Zend\Session\Exception\RuntimeException('You need to be connected to an Organisation's branch before you can add members. Contact your Organisation Owner.');
        }
    }
}

Am I missing something that second assertion is not working at all.


Solution

  • Just found that, isBranchOrOrgIdPresentIfNotAdmin entry has to be inside permission table and have to assign that permission to lower level of role inside hierarchicalrole_permission table (that permission will be given to upper level of role as well in hierarchical way automatically) and it will work fine for all of them.