PHP code example of api-skeletons / zf-oauth2-doctrine-permissions-acl

1. Go to this page and download the library: Download api-skeletons/zf-oauth2-doctrine-permissions-acl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

api-skeletons / zf-oauth2-doctrine-permissions-acl example snippets


'modules' => array(
   ...
   'ZF\OAuth2\Doctrine\Permissions\Acl',
),

'zf-oauth2-doctrine-permissions-acl' => [
    'role' => [
        'entity' => 'Db\Entity\Role',
        'object_manager' => 'doctrine.entitymanager.orm_default',
    ],
],

namespace Application;

use Zend\Mvc\MvcEvent;
use Zend\Mvc\ModuleRouteListener;
use Application\Authorization\AuthorizationListener;
use ZF\MvcAuth\MvcAuthEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $eventManager->attach(
            MvcAuthEvent::EVENT_AUTHORIZATION,
            new AuthorizationListener(),
            100 // Less than 1000 to allow roles to be added first && >= 100
        );
    }
}

namespace Application\Authorization;

use ZF\MvcAuth\MvcAuthEvent;
use Db\Fixture\RoleFixture;

class AuthorizationListener
{
    public function __invoke(MvcAuthEvent $mvcAuthEvent)
    {
        $authorization = $mvcAuthEvent->getAuthorizationService();

        // Deny from all
        $authorization->deny();

        // Allow from all for oauth authentication
        $authorization->addResource('ZF\OAuth2\Controller\Auth::token');
        $authorization->allow(null, 'ZF\OAuth2\Controller\Auth::token');

        // Add application specific resources
        $authorization->addResource('FooBar\V1\Rest\Foo\Controller::collection');
        $authorization->allow(RoleFixture::USER, 'FooBar\V1\Rest\Foo\Controller::collection', 'GET');
    }
}

use ZF\OAuth2\Doctrine\Permissions\Acl\Event;
use Zend\EventManager\Event as ZendEvent;

// Allow membership as a role
$events = $serviceManager->get('SharedEventManager');
$events->attach(
    Event::class,
    Event::IS_AUTHORIZED,
    function(ZendEvent $event)
    {
        if (! $event->getParam('identity') instanceof AuthenticatedIdentity) {
            return;
        }

        $membership = $event->getParam('identity')->getUser()->getMembership();

        if ($event->getTarget()->isAllowed($membership->getName(), $event->getParam('resource'), $event->getParam('privilege'))) {
            $event->stopPropagation();

            return true;
        }
    },
    100
);