Access Control Lists (ACL)
Phalcon\Acl provides an easy and lightweight management of ACLs as well as the permissions attached to them. (ACL) allow an application to control access to its areas and the underlying objects from requests.
In short, ACLs have two objects: The object that needs access, and the object that we need access to. In the programming world, these are usually referred to as Roles and Components. In the Phalcon world, we use the terminology Role and .
As seen above in the use case, an Role is defined as who needs to access a particular i.e. an area of the application. A Component is defined as the area of the application that needs to be accessed.
Using the component, we can tie those two together, and strengthen the security of our application, allowing only specific roles to be bound to specific components.
Creating an ACL
uses adapters to store and work with roles and components. The only adapter available right now is Phalcon\Acl\Adapter\Memory. Having the adapter use the memory, significantly increases the speed that the ACL is accessed but also comes with drawbacks. The main drawback is that memory is not persistent, so the developer will need to implement a storing strategy for the ACL data, so that the ACL is not generated at every request. This could easily lead to delays and unnecessary processing, especially if the ACL is quite big and/or stored in a database or file system.
Phalcon also offers an easy way for developers to build their own adapters by implementing the interface.
The Phalcon\Acl constructor takes as its first parameter an adapter used to retrieve the information related to the control list.
There are two self explanatory actions that the provides:
Phalcon\Acl\Enum::DENY
The default action isPhalcon\Acl\Enum::DENY
for any Role or . This is on purpose to ensure that only the developer or application allows access to specific components and not the ACL component itself.
<?php
use Phalcon\Acl\Enum;
use Phalcon\Acl\Adapter\Memory as AclList;
$acl = new AclList();
$acl->setDefaultAction(Enum::ALLOW);
Adding Roles
As mentioned above, a is an object that can or cannot access a set of Component in the access list.
There are two ways of adding roles to our list.
- by using a object or
- using a string, representing the name of the roleTo see this in action, using the example outlined above, we will add the relevant Phalcon\Acl\Role objects in our list.
Role objects. The first parameter is the name of the role, the second the description
<?php
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
$acl = new AclList();
$roleAdmins = new Role('admins', 'Administrator Access');
$roleAccounting = new Role('accounting', 'Accounting Department Access');
$acl->addRole($roleAdmins);
$acl->addRole($roleAccounting);
Strings. Add the role with just the name directly to the ACL:
<?php
use Phalcon\Acl\Adapter\Memory as AclList;
$acl = new AclList();
$acl->addRole('manager');
$acl->addRole('guest');
Adding Components
There are two ways of adding components to our list.
- by using a Phalcon\Acl\Component object or
- using a string, representing the name of the roleSimilar to the
addRole
,addComponent
requires a name for the component and an optional description.
Component objects. The first parameter is the name of the component, the second the description
<?php
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Component;
$acl = new AclList();
$admin = new Component('admin', 'Administration Pages');
$reports = new Component('reports', 'Reports Pages');
$acl->addComponent(
$admin,
[
'dashboard',
'users',
]
);
$acl->addComponent(
$reports,
[
'list',
'add',
]
);
Strings. Add the component with just the name directly to the ACL:
<?php
use Phalcon\Acl\Adapter\Memory as AclList;
$acl = new AclList();
$acl->addComponent(
'admin',
[
'dashboard',
'users',
]
);
$acl->addComponent(
'reports',
[
'list',
'add',
]
);
After both the Roles
and Components
have been defined, we need to tie them together so that the access list can be created. This is the most important step in the role since a small mistake here can allow access to roles for components that the developer does not intend to. As mentioned earlier, the default access action for is Phalcon\Acl\Enum::DENY
, following the whitelist approach.
To tie Roles
and Components
together we use the allow()
and deny()
methods exposed by the class.
<?php
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
use Phalcon\Acl\Component;
$acl = new AclList();
/**
* Add the roles
*/
$acl->addRole('manager');
$acl->addRole('accounting');
$acl->addRole('guest');
/**
* Add the Components
*/
$acl->addComponent(
'admin',
[
'dashboard',
'users',
'view',
]
);
$acl->addComponent(
'reports',
[
'list',
'add',
'view',
]
);
$acl->addComponent(
'session',
[
'login',
'logout',
]
);
/**
* Now tie them all together
*/
$acl->allow('manager', 'admin', 'users');
$acl->allow('manager', 'reports', ['list', 'add']);
$acl->allow('*', 'session', '*');
$acl->allow('*', '*', 'view');
$acl->deny('guest', '*', 'view');
What the above lines tell us:
$acl->allow('manager', 'admin', 'users');
For the manager
role, allow access to the admin
component and users
action. To bring this into perspective with a MVC application, the above line says that the group manager
is allowed to access the admin
controller and users
action.
You can also pass an array as the action
parameter when invoking the allow()
command. The above means that for the manager
role, allow access to the reports
component and list
and add
actions. Again to bring this into perspective with a MVC application, the above line says that the group manager
is allowed to access the reports
controller and list
and add
actions.
$acl->allow('*', 'session', '*');
Wildcards can also be used to do mass matching for roles, components or actions. In the above example, we allow every role to access every action in the session
component. This command will give access to the manager
, accounting
and guest
roles, access to the session
component and to the login
and logout
actions.
$acl->allow('*', '*', 'view');
Similarly the above gives access to any role, any component that has the view
action. In a MVC application, the above is the equivalent of allowing any group to access any controller that exposes a viewAction
.
$acl->deny('guest', '*', 'view');
For the guest
role, we deny access to all components with the view
action. Despite the fact that the default access level is Acl\Enum::DENY
in our example above, we specifically allowed the view
action to all roles and components. This includes the guest
role. We want to allow the guest
role access only to the session
component and the login
and logout
actions, since guests
are not logged into our application.
$acl->allow('*', '*', 'view');
This gives access to the view
access to everyone, but we want the guest
role to be excluded from that so the following line does what we need.
Querying
Once the list has been defined, we can query it to check if a particular role has access to a particular component and action. To do so, we need to use the isAllowed()
method.
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
use Phalcon\Acl\Component;
$acl = new AclList();
/**
* Setup the ACL
*/
$acl->addRole('manager');
$acl->addRole('accounting');
$acl->addRole('guest');
$acl->addComponent(
'admin',
[
'dashboard',
'users',
'view',
]
);
$acl->addComponent(
'reports',
[
'list',
'add',
'view',
]
);
$acl->addComponent(
'session',
[
'login',
'logout',
]
);
$acl->allow('manager', 'admin', 'users');
$acl->allow('manager', 'reports', ['list', 'add']);
$acl->allow('*', 'session', '*');
$acl->allow('*', '*', 'view');
$acl->deny('guest', '*', 'view');
// ....
// true - defined explicitly
$acl->isAllowed('manager', 'admin', 'dashboard');
// true - defined with wildcard
$acl->isAllowed('manager', 'session', 'login');
// true - defined with wildcard
$acl->isAllowed('accounting', 'reports', 'view');
// false - defined explicitly
$acl->isAllowed('guest', 'reports', 'view');
// false - default access level
$acl->isAllowed('guest', 'reports', 'add');
Function based access
Depending on the needs of your application, you might need another layer of calculations to allow or deny access to users through the ACL. The method isAllowed()
accepts a 4th parameter which is a callable such as an anonymous function.
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
use Phalcon\Acl\Component;
$acl = new AclList();
/**
* Setup the ACL
*/
$acl->addRole('manager');
$acl->addComponent(
'admin',
[
'dashboard',
'users',
'view',
]
);
// Set access level for role into components with custom function
$acl->allow(
'manager',
'admin',
'dashboard',
function ($name) {
return boolval('Bob' !== $name);
}
);
Now that the callable is defined in the ACL, we will need to call the isAllowed()
method with an array as the fourth parameter:
You can also omit to pass the fourth parameter to isAllowed()
if you wish. The default action for a call to isAllowed()
without the last parameter is Acl\Enum::DENY
. To change this behavior, you can make a call to setNoArgumentsDefaultAction()
:
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
use Phalcon\Acl\Component;
$acl = new AclList();
/**
* Setup the ACL
*/
$acl->addRole('manager');
$acl->addComponent(
'admin',
[
'dashboard',
'users',
'view',
]
);
// Set access level for role into components with custom function
$acl->allow(
'manager',
'admin',
'dashboard',
function ($name) {
return boolval('Bob' !== $name);
}
);
// Returns false
$acl->isAllowed('manager', 'admin', 'dashboard');
$acl->setNoArgumentsDefaultAction(
Acl\Enum::ALLOW
);
// Returns true
$acl->isAllowed('manager', 'admin', 'dashboard');
Objects as role name and component name
Phalcon allows developers to define their own role and component objects. These objects must implement the supplied interfaces:
- for Role
- Phalcon\Acl\ComponentAware for Component
We can implement the in our custom class with its own logic. The example below shows a new role object called ManagerRole
:
<?php
use Phalcon\Acl\RoleAware;
// Create our class which will be used as roleName
class ManagerRole implements RoleAware
{
protected $id;
protected $roleName;
public function __construct($id, $roleName)
{
$this->id = $id;
$this->roleName = $roleName;
}
public function getId()
{
return $this->id;
}
// Implemented function from RoleAware Interface
public function getRoleName()
{
return $this->roleName;
}
}
We can implement the Phalcon\Acl\ComponentAware in our custom class with its own logic. The example below shows a new role object called ReportsComponent
:
<?php
use Phalcon\Acl\ComponentAware;
// Create our class which will be used as componentName
class ReportsComponent implements ComponentAware
{
protected $componentName;
protected $userId;
public function __construct($id, $componentName, $userId)
{
$this->id = $id;
$this->componentName = $componentName;
$this->userId = $userId;
}
public function getId()
{
return $this->id;
}
public function getUserId()
{
return $this->userId;
}
// Implemented function from ComponentAware Interface
public function getComponentName()
{
return $this->componentName;
}
}
These objects can now be used in our ACL.
<?php
use ManagerRole;
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
use Phalcon\Acl\Component;
use ReportsComponent;
$acl = new AclList();
/**
* Add the roles
*/
$acl->addRole('manager');
/**
* Add the Components
*/
$acl->addComponent(
'reports',
[
'list',
'add',
'view',
]
);
/**
* Now tie them all together with a custom function. The ManagerRole and
* ModelSbject parameters are necessary for the custom function to work
*/
$acl->allow(
'manager',
'reports',
'list',
function (ManagerRole $manager, ModelComponent $model) {
return boolval($manager->getId() === $model->getUserId());
}
);
// Create the custom objects
$levelOne = new ManagerRole(1, 'manager-1');
$levelTwo = new ManagerRole(2, 'manager');
$admin = new ManagerRole(3, 'manager');
// id - name - userId
$reports = new ModelComponent(2, 'reports', 2);
// Check whether our user objects have access
// Returns false
$acl->isAllowed($levelOne, $reports, 'list');
// Returns true
$acl->isAllowed($levelTwo, $reports, 'list');
// Returns false
$acl->isAllowed($admin, $reports, 'list');
The second call for $levelTwo
evaluates true
since the getUserId()
returns 2
which in turn is evaluated in our custom function. Also note that in the custom function for allow()
the objects are automatically bound, providing all the data necessary for the custom function to work. The custom function can accept any number of additional parameters. The order of the parameters defined in the function()
constructor does not matter, because the objects will be automatically discovered and bound.
To remove duplication and increase efficiency in your application, the ACL offers inheritance in roles. This means that you can define one as a base and after that inherit from it offering access to supersets or subsets of components. To use role inheritance, you need, you need to pass the inherited role as the second parameter of the method call, when adding that role in the list.
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
$acl = new AclList();
/**
* Create the roles
*/
$manager = new Role('Managers');
$accounting = new Role('Accounting Department');
$guest = new Role('Guests');
/**
* Add the `guest` role to the ACL
*/
$acl->addRole($guest);
/**
* Add the `accounting` inheriting from `guest`
*/
$acl->addRole($accounting, $guest);
/**
* Add the `manager` inheriting from `accounting`
*/
$acl->addRole($manager, $accounting);
Whatever access guests
have will be propagated to accounting
and in turn accounting
will be propagated to manager
Based on the application design, you might prefer to add first all the roles and then define the relationship between them.
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Role;
$acl = new AclList();
/**
* Create the roles
*/
$manager = new Role('Managers');
$accounting = new Role('Accounting Department');
$guest = new Role('Guests');
/**
* Add all the roles
*/
$acl->addRole($manager);
$acl->addRole($accounting);
$acl->addRole($guest);
/**
* Add the inheritance
*/
$acl->addInherit($manager, $accounting);
$acl->addInherit($accounting, $guest);
Serializing ACL lists
can be serialized and stored in a cache system to improve efficiency. You can store the serialized object in APC, session, file system, database, Redis etc. This way you can retrieve the ACL quickly without having to read the underlying data that create the ACL nor will you have to compute the ACL in every request.
<?php
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
$aclFile = 'app/security/acl.cache';
// Check whether ACL data already exist
if (true !== is_file($aclFile)) {
// The ACL does not exist - build it
$acl = new AclList();
// ... Define roles, components, access, etc
// Store serialized list into plain file
file_put_contents(
$aclFile,
serialize($acl)
);
} else {
// Restore ACL object from serialized file
$acl = unserialize(
file_get_contents($aclFile)
);
}
// Use ACL list as needed
if (true === $acl->isAllowed('manager', 'admin', 'dashboard')) {
echo 'Access granted!';
} else {
}
It is a good practice to not use serialization of the ACL during development, to ensure that your ACL is built in every request, while other adapters or means of serializing and storing the ACL in production.
Events
can work in conjunction with the EventsManager if present, to fire events to your application. Events are triggered using the type acl
. Events that return false
can stop the active role. The following events are available:
The following example demonstrates how to attach listeners to the ACL:
Implementing your own adapters
The Phalcon\Acl\AdapterInterface interface must be implemented in order to create your own ACL adapters or extend the existing ones.