Thursday, January 8, 2009

Zend framework Zend_Acl

Acl stands for action control list.

The typical flow for using Zend_Acl in a web application is as follows:
1. Instantiate the Zend_Acl class (let’s call this object $acl).
2. Add one or more roles to $acl using the addRole() method.
3. Add resources to $acl using the add() method.
4. Add the full list of privileges for each role (that is, use allow() or deny() to indicate which resources roles have access to).
5. Use the isAllowed() method on $acl to determine whether a particular role has access
to a particular resource/privilege combination.
6. Repeat step 5 as often as necessary while the script executes.

$this->auth = $auth;
$this->acl = new Zend_Acl();
//add the different user role
$this->acl->addRole(new Zend_Acl_Role($this->_defaultRole));
$this->acl->addRole(new Zend_Acl_Role('admin'));
$this->acl->addRole(new Zend_Acl_Role('member'));
$this->acl->addRole(new Zend_Acl_Role('administrator'), 'member');
// add the resources we want to have control over
$this->acl->add(new Zend_Acl_Resource('account'));
$this->acl->add(new Zend_Acl_Resource('admin'));

// allow access to everything for all users by default
// except for the account management and administration areas
$this->acl->deny(null, 'account');
$this->acl->deny(null, 'admin');
// add an exception so guests can log in or register
// in order to gain privilege
$this->acl->allow('guest', 'account', array('login', 'fetchpassword' , 'register' , 'registercomplete'));
// allow members access to the account management area
$this->acl->allow('member', 'account');
$this->acl->allow('admin', 'admin');

public function preDispatch (Zend_Controller_Request_Abstract $request)
// check if a user is logged in and has a valid role,
// otherwise, assign them the default role (guest)
if ($this->auth->hasIdentity()) {
$role = $this->auth->getIdentity()->subscription_type;
} else {
$role = $this->_defaultRole;
if (! $this->acl->hasRole($role)) {
$role = $this->_defaultRole;
// the ACL resource is the requested controller name
$resource = $request->controller;
// the ACL privilege is the requested action name
$privilege = $request->action;
// if we haven't explicitly added the resource, check
// the default global permissions
if (! $this->acl->has($resource))
$resource = null;
// access denied - reroute the request to the default action handler
if (! $this->acl->isAllowed($role, $resource, $privilege)) {

in bootstrap file, we add
$frontController->registerPlugin(new ControllerAclManager($auth));

No comments: