111 lines
2.8 KiB
PHP
111 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace Httpcb;
|
|
|
|
use Phalcon\Config,
|
|
Phalcon\Acl\Enum,
|
|
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(Enum::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') == Enum::ALLOW;
|
|
}
|
|
|
|
/**
|
|
* @param string $resource
|
|
* @return bool
|
|
*/
|
|
public function hasResource($resource)
|
|
{
|
|
return $this->_adapter->isComponent($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->addComponent($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) {
|
|
$resources = $config->zones->get($zone);
|
|
if (!($resources instanceof Config)) {
|
|
$resources = new Config([$resources]);
|
|
}
|
|
foreach ($resources as $resource) {
|
|
$this->_adapter->allow($name, $resource, 'All');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|