Skip to content

Instantly share code, notes, and snippets.

@starbuckit
Created December 27, 2015 01:08
Show Gist options
  • Save starbuckit/f75ae30e11a62bcabb7e to your computer and use it in GitHub Desktop.
Save starbuckit/f75ae30e11a62bcabb7e to your computer and use it in GitHub Desktop.
<?php
use Phalcon\Mvc\Dispatcher,
Phalcon\Events\Event;
class Permission extends \Phalcon\Mvc\User\Plugin
{
/**
* Constants to prevent typo
*/
const GUEST = 'guest';
const USER = 'user';
const ADMIN = 'admin';
protected $_publicResources = [
'index' => '*',
'signin' => '*'
];
protected $_userResources =[
'dashboard' => ['*']
];
protected $_adminResources = [
'admin' => ['*']
];
public function _getAcl()
{
if(!isset($this->persistent->acl))
{
$acl = new \Phalcon\Acl\Adapter\Memory();
$acl->setDefaultAction(Phalcon\Acl::DENY);
$roles = [
self::GUEST => new \Phalcon\Acl\Role(self::GUEST),
self::USER => new \Phalcon\Acl\Role(self::USER),
self::ADMIN => new \Phalcon\Acl\Role(self::ADMIN),
];
foreach ($roles as $role) {
$acl->addRole($role);
}
//Public Resources
foreach ($this->_publicResources as $resource => $actions) {
$acl->addResource(new \Phalcon\Acl\Resource($resource), $actions);
}
//User Resources
foreach ($this->_userResources as $resource => $actions) {
$acl->addResource(new \Phalcon\Acl\Resource($resource), $actions);
}
//Admin Resources
foreach ($this->_adminResources as $resource => $actions) {
$acl->addResource(new \Phalcon\Acl\Resource($resource), $actions);
}
//Allow All Roles to access the public Resources
foreach ($roles as $role) {
foreach($this->_publicResources as $resource => $actions) {
$acl->allow($role->getName(), $resource, '*');
}
}
//Allow User & Admin to access the User Resources
foreach ($this->_userResources as $resource => $actions ) {
foreach ($actions as $action) {
$acl->allow(self::USER, $resource, $action);
$acl->allow(self::ADMIN, $resource, $action);
}
}
//Allow Admin to access the Admin Resources
foreach ($this->_adminResources as $resource => $actions ) {
foreach ($actions as $action) {
$acl->allow(self::ADMIN, $resource, $action);
}
}
}
return $this->persistent->acl;
}
public function beforeExecuteRoute( Event $event, Dispatcher $dispatcher)
{
$role = $this->session->get('role');
if(!$role) {
$role = self::GUEST;
}
//Get the current controller/action from dispatcher
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
//Get the ACL Rule List
$acl = $this->_getAcl();
//See if they have permission
$allowed = $acl->isAllowed($role, $controller, $action);
if ($allowed != Phalcon\Acl::ALLOW)
{
$dispatcher->forward([
'controller' => 'index',
'action' => 'index'
]);
//Stop the dispatcher at the current operation
return false;
}
}
}
@starbuckit
Copy link
Author

return $acl;
instead of
return $this->persistent->acl;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment