107 lines
2.6 KiB
PHP
107 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace Httpcb;
|
|
|
|
use Phalcon\Config,
|
|
Phalcon\Acl\Role,
|
|
Phalcon\Acl\Adapter\Memory as Adapter;
|
|
|
|
class Acl
|
|
{
|
|
const ROLE_USER = 'user';
|
|
const ROLE_GUEST = 'guest';
|
|
|
|
/**
|
|
* @var Adapter
|
|
*/
|
|
protected $_adapter = null;
|
|
|
|
public function __construct(Config $config)
|
|
{
|
|
$this->_adapter = new Adapter();
|
|
|
|
// Deny access to everything by default.
|
|
$this->_adapter->setDefaultAction(\Phalcon\Acl::DENY);
|
|
|
|
$this->fromConfig($config);
|
|
}
|
|
|
|
/**
|
|
* @param $role
|
|
* @param $resource
|
|
* @return bool
|
|
*/
|
|
public function isAllowed($role, $resource)
|
|
{
|
|
// Special stuff here :) for resources within modules.
|
|
|
|
// Modules and controllers are separated by "/"
|
|
$pos = strpos($resource, '/');
|
|
if ($pos !== false) {
|
|
// Construct the wildcard resource.
|
|
$wildcard = substr($resource, 0, $pos+1) . '*';
|
|
|
|
// If we have this wildcard resource, check against that instead.
|
|
if ($this->hasResource($wildcard)) {
|
|
$resource = $wildcard;
|
|
}
|
|
}
|
|
return $this->_adapter->isAllowed($role, $resource, 'All') == \Phalcon\Acl::ALLOW;
|
|
}
|
|
|
|
/**
|
|
* @param string $resource
|
|
* @return bool
|
|
*/
|
|
public function hasResource($resource)
|
|
{
|
|
return $this->_adapter->isResource($resource);
|
|
}
|
|
|
|
public function fromConfig(Config $config)
|
|
{
|
|
// Add roles.
|
|
foreach($config->roles as $name => $def) {
|
|
|
|
$inherits = null;
|
|
$description = null;
|
|
|
|
if ($def instanceof Config) {
|
|
$inherits = $def->get('inherits');
|
|
$description = $def->get('description');
|
|
|
|
}
|
|
|
|
$role = new Role($name, $description);
|
|
$this->_adapter->addRole($role, $inherits);
|
|
}
|
|
|
|
// Zones
|
|
foreach($config->zones as $name => $resources) {
|
|
|
|
if (!($resources instanceof Config)) {
|
|
$resources = new Config([ $resources ]);
|
|
}
|
|
|
|
foreach($resources as $resource) {
|
|
$this->_adapter->addResource($resource, 'All');
|
|
}
|
|
}
|
|
|
|
// Grant access for roles and resources.
|
|
foreach($config->roles as $name => $def) {
|
|
|
|
$zones = $def->get('allowed-zones', []);
|
|
|
|
if (is_string($zones)) {
|
|
$zones = [ $zones ];
|
|
}
|
|
|
|
foreach($zones as $zone) {
|
|
foreach($config->zones->get($zone) as $resource) {
|
|
$this->_adapter->allow($name, $resource, 'All');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|