Thursday, September 12, 2019

Using Zend ACL for Dynamic Access Control Privileges from Specifics Database

Zend ACL is flexible access control list implementation for  privileges management. Zend ACL has 3 different area Resources, Role, and Rights.

  • Resources : Object which access is controlled.
  • Role: Object which can request access to resources.
  • Right:  Access Role for access resources.
As a default, Zend ACL give deny value to all resources, we have to built white list access roles for each of resources.
In this example, I will use "user_role" table as Resources, "role_access" table as Rights. 

$acl = new Zend_Acl();

// Load Roles from DB
$sql = 'SELECT role_slug FROM '.TB_PREFIX.'user_role';
$roles = dbQuery($sql);
$roles = $roles->fetchAll();

/*
 * 
$roles= array();  
 1  => array(
          'name' => Administrator,
         ),
 2  => array(
          'name' => User,
         ),
 *
 */

//create the resources for API
$acl->add(new Zend_Acl_Resource('api'));

// create the Resources
foreach ($roles as $role) {
$acl->addRole(new Zend_Acl_Role($role['name']));
}

/*
 * Add whitelist for API
 */
// everyone see auth page
$acl->allow(null,'auth');
// everyone see api page
$acl->allow(null,'api');

// Administrator inherits nothing, but is allowed all privileges
$acl->allow('administrator');

// To check permissions
$checkPermission = new Zend_Session_Namespace('Zend_Auth');

// Set role access from DB
$sql = 'SELECT * FROM '.TB_PREFIX.'role_access as ra JOIN
      '.TB_PREFIX.'user_role ur ON (ra.role_id = ur.id) WHERE role_id = '.$auth_session->role_id;
$role_access = dbQuery($sql);
$role_access = $role_access->fetchAll();

foreach ($role_access as $role_access_data) {
$is_allow = array();

    // assign if role acess is existed
   if (count($is_allow) > 0) 
  {
$acl->allow($role_access_data['role_slug'], $role_access_data['module'], $is_allow);
$checkPermission->$role_access_data['module'] = $acl->isAllowed($auth_session->role_name, $role_access_data['module'],"manage");
  }
}
Share:

0 comments:

Post a Comment