Access Control

Create Access Control List

<?php

namespace App\Acl\Adapter;

use PhalconRest\Acl\MountingEnabledAdapterInterface;
use Phalcon\Acl\Adapter\Memory as MemoryAdapter;

class Memory extends MemoryAdapter implements MountingEnabledAdapterInterface
{
    use \AclAdapterMountTrait;
}

Create roles

<?php

/** @var \PhalconRest\Acl\MountingEnabledAdapterInterface $acl */
$acl = $di->get(Services::ACL);


// These are our main roles
$unauthorizedRole = new Acl\Role(AclRoles::UNAUTHORIZED);

$authorizedRole = new Acl\Role(AclRoles::AUTHORIZED);


// We register them on the acl
$acl->addRole($unauthorizedRole);

$acl->addRole($authorizedRole);


// All the following roles extend either from the authorizedRole or the
// unauthorized role.
$acl->addRole(new Acl\Role(AclRoles::ADMINISTRATOR), $authorizedRole);

$acl->addRole(new Acl\Role(AclRoles::MANAGER), $authorizedRole);

$acl->addRole(new Acl\Role(AclRoles::USER), $authorizedRole);


// Because the acl we use implements the `MountingEnabledAdapterInterface`
// we are allowed to mount our Resources on it.
$acl->mountMany($api->getResources());

Restrict access on Resources

<?php

$api->resource(Resource::crud('/users', 'User')

    // Here we restrict access to all endpoints
    // on this Resource. The `User` role is not allowed
    // to access all endpoints by default.
    ->deny(AclRoles::UNAUTHORIZED, AclRoles::USER)

    // Because access can be overridden,
    // we specifically allow access for
    // the `User` role on this endpoint.
    ->endpoint(Endpoint::get('/me', 'me')
        ->allow(AclRoles::USER)
        // .. more endpoint setup
    )

    // When a user has already been authenticated, it doesn't
    // make sense to let them gain access on this endpoint.
    ->endpoint(Endpoint::post('/authenticate', 'authenticate')
        ->allow(AclRoles::UNAUTHORIZED)
        ->deny(AclRoles::AUTHORIZED)
        // .. more endpoint setup
    )

    // .. more resource setup
);