public function initialAclRole($e, $serviceAdministratorConfigManager, $authenticationServiceStorage) { $oAcl = new Acl(); $oAcl->deny(); $oAcl->addRole(new Role('staff_1')); $oAcl->addRole(new Role('staff_2')); $oAcl->addRole(new Role('administrator')); $oAcl->addResource('administrator'); $oAcl->addResource('api'); $oAcl->allow('staff_1', 'administrator', 'index:index'); $oAcl->allow('staff_1', 'administrator', 'user:profile'); $oAcl->allow('staff_1', 'administrator', 'user:list'); $oAcl->allow('staff_1', 'administrator', 'menu:list'); $controllerClass = get_class($e->getTarget()); $moduleName = strtolower(substr($controllerClass, 0, strpos($controllerClass, '\\'))); $routeMatch = $e->getRouteMatch(); $aName = strtolower($routeMatch->getParam('action', 'not-found')); $cName = strtolower($routeMatch->getParam('__CONTROLLER__', 'not-found')); /* if (!$oAcl->isAllowed("staff_1",$moduleName, "{$cName}:{$aName}")) { $response = $e->getResponse(); $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', $e->getRouter()->assemble($serviceAdministratorConfigManager['options']['constraints'], array('name' => $_SERVER['HTTP_HOST']. '/'. 'default'))); $e->stopPropagation(); } */ }
/** * @return Acl */ protected function roleAcl() { if (!$this->roleAcl) { $id = $this->objId(); $this->roleAcl = new Acl(); $this->roleAcl->addRole(new Role($id)); $this->roleAcl->addResource(new Resource('admin')); $q = ' select `denied`, `allowed`, `superuser` from `charcoal_admin_acl_roles` where ident = :id'; $db = \Charcoal\App\App::instance()->getContainer()->get('database'); $sth = $db->prepare($q); $sth->bindParam(':id', $id); $sth->execute(); $permissions = $sth->fetch(\PDO::FETCH_ASSOC); $this->roleAllowed = explode(',', trim($permissions['allowed'])); $this->roleDenied = explode(',', trim($permissions['denied'])); foreach ($this->roleAllowed as $allowed) { $this->roleAcl->allow($id, 'admin', $allowed); } foreach ($this->roleDenied as $denied) { $this->roleAcl->deny($id, 'admin', $denied); } } return $this->roleAcl; }
/** * AccessControl constructor. * @param $config * @param $entityManager * @param $userMapper * @param $roleMapper * @param $resourceMapper */ public function __construct($config, $entityManager, $userMapper, $roleMapper, $resourceMapper) { $this->setConfig($config); $this->setEntityManager($entityManager); $this->setUserMapper($userMapper); $this->setRoleMapper($roleMapper); $this->setResourceMapper($resourceMapper); $this->modules = $this->getConfig()['mfcc_admin']['modules']; $this->acl = new Acl(); foreach ($this->getRoleMapper()->getAll() as $index => $role) { /* @var $role RoleEntity */ $this->acl->addRole(new Role($role->getName())); } foreach ($this->modules as $index => $module) { $this->acl->addResource(new GenericResource($module['module_name'])); } $this->acl->addResource(new GenericResource('Users')); $this->acl->addResource(new GenericResource('Roles')); foreach ($this->getResourceMapper()->getAll() as $index => $resource) { /* @var $resource ResourceEntity */ $this->acl->allow($resource->getRole()->getName(), $resource->getResource(), $resource->getPermission()); if ($resource->getPermission() == self::WRITE) { $this->acl->allow($resource->getRole()->getName(), $resource->getResource(), self::READ); } } }
public function doAuthorization($e) { return; //setting ACL... $acl = new Acl(); //add role .. $acl->addRole(new Role('anonymous')); $acl->addRole(new Role('user'), 'anonymous'); $acl->addRole(new Role('admin'), 'user'); $acl->addResource(new Resource('Stick')); $acl->addResource(new Resource('Auth')); $acl->deny('anonymous', 'Stick', 'list'); $acl->allow('anonymous', 'Auth', 'login'); $acl->allow('anonymous', 'Auth', 'signup'); $acl->allow('user', 'Stick', 'add'); $acl->allow('user', 'Auth', 'logout'); //admin is child of user, can publish, edit, and view too ! $acl->allow('admin', 'Stick'); $controller = $e->getTarget(); $controllerClass = get_class($controller); $namespace = substr($controllerClass, strrpos($controllerClass, '\\') + 1); $role = !$this->getSessContainer()->role ? 'anonymous' : $this->getSessContainer()->role; echo $role; exit; if (!$acl->isAllowed($role, $namespace, 'view')) { $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'Login/auth')); $response = $e->getResponse(); $response->setStatusCode(302); //redirect to login route... $response->getHeaders()->addHeaderLine('Location', $url); } }
public function __invoke($serviceLocator) { $config = $serviceLocator->get('config'); $this->acl = $serviceLocator->get('MultiRoleAclBase\\Service\\MultiRolesAcl'); if (get_class($this->acl) == 'MultiRoleAclBase\\Service\\MultiRolesAcl' || is_subclass_of($this->acl, 'MultiRoleAclBase\\Service\\MultiRolesAcl')) { $this->acl->setAllowAccessWhenResourceUnknown(false); } $this->roleBuilder = $serviceLocator->get('MultiRoleAclBase\\Acl\\Builder\\RoleBuilder'); $this->resourceBuilder = $serviceLocator->get('MultiRoleAclBase\\Acl\\Builder\\ResourceBuilder'); $this->ruleBuilder = $serviceLocator->get('MultiRoleAclBase\\Acl\\Builder\\RuleBuilder'); // Get all Roles from RoleBuilder $roles = $this->roleBuilder->buildRoles($this->acl, $serviceLocator); if (is_array($roles)) { foreach ($roles as $role) { $this->acl->addRole($role); } } // Get all Resources from ResourceBuilder $resources = $this->resourceBuilder->buildResources($this->acl, $serviceLocator); if (is_array($resources)) { foreach ($resources as $resource) { $this->acl->addResource($resource); } } // Build all the rules $this->ruleBuilder->buildRules($this->acl, $serviceLocator); return $this->acl; }
/** * Constructor * * @param array $roles * @param array $resources */ public function __construct($roles, $resources) { //Create brand new Acl object $this->acl = new Acl(); //Add each resources foreach ($resources as $resource) { //Add the resource $this->acl->addResource(new Resource($resource)); } //Add each roles foreach ($roles as $role => $resources) { //Add the role $this->acl->addRole(new Role($role)); //If we want to grant all privileges on all resources if ($resources === true) { //Allow all privileges $this->acl->allow($role); //Else if we have specific privileges for the role } elseif (is_array($resources)) { //Create each resource permissions foreach ($resources as $resource => $permissions) { //Add resource permissions of the role $this->acl->allow($role, $resource, $permissions); } } } }
public function doAuthorization($e) { //setting ACL... $acl = new Acl(); //add role .. $acl->addRole(new Role('anonymous')); $acl->addRole(new Role('user'), 'anonymous'); $acl->addRole(new Role('admin'), 'user'); $acl->addResource(new Resource('Application')); $acl->addResource(new Resource('Login')); $acl->addResource(new Resource('ZfcAdmin')); $acl->deny('anonymous', 'Application', 'view'); $acl->allow('anonymous', 'Login', 'view'); $acl->allow('user', array('Application'), array('view')); //admin is child of user, can publish, edit, and view too ! $acl->allow('admin', array('Application'), array('publish', 'edit')); $controller = $e->getTarget(); $controllerClass = get_class($controller); //echo "<pre>";print_r($controllerClass);exit; $namespace = substr($controllerClass, 0, strpos($controllerClass, '\\')); // echo "<pre>";print_r($namespace);exit; $role = !$this->getSessContainer()->role ? 'anonymous' : $this->getSessContainer()->role; if (!isset($_SESSION['admin']['user_id']) && $namespace == 'ZfcAdmin') { $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'zfcadmin')); $response = $e->getResponse(); $response->setStatusCode(302); //redirect to login route... /* change with header('location: '.$url); if code below not working */ $response->getHeaders()->addHeaderLine('Location', $url); $e->stopPropagation(); } }
/** * AclRepository constructor. * * the user_id injected should be a "role name" * Each Role would actually be a user. * Then each User can have 1 or more different roles * which then correspond to one or more different resources * * $aclList = [ * "resources" => [list of resources names] * "roles" => [list of role names] * "assignments" => [ * "allow" => [ * "rolename" => [list of resources] * ] * "deny" => [ * "rolename" => [list of resources] * ] * ] * * * @param string $role This is the current Role(s) you are testing for * @param array $aclList */ public function __construct(array $role, array $aclList = []) { $this->acl = new Acl(); $this->role = $role; if (isset($aclList['resources'])) { foreach ($aclList['resources'] as $resource) { $this->acl->addResource($this->makeResource($resource)); } } if (isset($aclList['roles'])) { foreach ($aclList['roles'] as $role) { $this->acl->addRole($this->makeRole($role)); } } if (isset($aclList['assignments'])) { foreach ($aclList['assignments']['allow'] as $role => $resources) { foreach ($resources as $resource) { $this->addAllow($role, $resource); } } foreach ($aclList['assignments']['deny'] as $role => $resources) { foreach ($resources as $resource) { $this->addDeny($role, $resource); } } } }
public function initAcl(MvcEvent $e) { //Creamos el objeto ACL $acl = new Acl(); //Incluimos la lista de roles y permisos, nos devuelve un array $roles = (require 'config/autoload/acl.roles.php'); foreach ($roles as $role => $resources) { //Indicamos que el rol será genérico $role = new \Zend\Permissions\Acl\Role\GenericRole($role); //Añadimos el rol al ACL $acl->addRole($role); //Recorremos los recursos o rutas permitidas foreach ($resources["allow"] as $resource) { //Si el recurso no existe lo añadimos if (!$acl->hasResource($resource)) { $acl->addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource)); } //Permitimos a ese rol ese recurso $acl->allow($role, $resource); } foreach ($resources["deny"] as $resource) { //Si el recurso no existe lo añadimos if (!$acl->hasResource($resource)) { $acl->addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource)); } //Denegamos a ese rol ese recurso $acl->deny($role, $resource); } } //Establecemos la lista de control de acceso $e->getViewModel()->acl = $acl; }
public function loginAction() { $authenticationService = new AuthenticationService(); if ($authenticationService->hasIdentity()) { return $this->redirect()->toRoute('dashboard'); } $form = new LoginForm(); $viewModel = new ViewModel(); $this->layout("layout/login"); $viewModel->setVariable("form", $form); $viewModel->setVariable("config", $this->config); $request = $this->getRequest(); if ($request->isPost()) { $login = new Login(); $login->getInputFilter()->get('captcha')->setRequired(false); $form->setInputFilter($login->getInputFilter()); $form->setData($request->getPost()); if ($form->isValid()) { $username = $form->get('username')->getValue(); $password = $form->get('password')->getValue(); $authSessionAdapter = $this->getAuthSessionAdapter(); if ($authSessionAdapter->authenticate($username, $password)) { $userObject = $authenticationService->getStorage()->read(); $rol = $userObject->rol; $acl = new Acl(); $acl->addResource(new Resource("dashboard")); $acl->addResource(new Resource("note")); if ($rol == 1) { $resources = $this->config['resources']; foreach ($resources as $module => $resource) { foreach ($resource as $resourceValue) { $acl->addResource(new Resource($resourceValue)); } } } else { $acl->addRole(new Role($rol)); $modules = $this->getModuleRolTable()->fetchAll($rol); foreach ($modules as $module) { $acl->addResource(new Resource($module)); } } $userObject->acl = serialize($acl); return $this->redirect()->toRoute('dashboard'); } else { $form->get('username')->setValue(""); $form->get('password')->setValue(""); if ($authSessionAdapter->getCode() == -5) { $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][$authSessionAdapter->getCode()])); } else { $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6])); } } } else { $form->get("username")->setMessages(array('username' => $this->config['authentication_codes'][-6])); } } return $viewModel; }
private function _load() { if ($this->loaded == false) { // Add roles $config = $this->serviceLocator->get('config'); if (isset($config['acl']['role_providers'])) { $roles = []; foreach ($config['acl']['role_providers'] as $class => $options) { /** @var \Acl\Provider\Role\ProviderInterface $roleProvider */ $roleProvider = $this->serviceLocator->get($class); $roles = $roles + $roleProvider->getRoles(); } foreach ($roles as $role) { /** @var \Acl\Entity\Role $role */ $this->acl->addRole($role, $role->getParents()); } } // Add resources if (isset($config['acl']['resource_providers'])) { foreach ($config['acl']['resource_providers'] as $class => $options) { /** @var \Acl\Provider\Resource\ProviderInterface $resourceProvider */ $resourceProvider = $this->serviceLocator->get($class); $resources = $resourceProvider->getResources(); if ($resources) { foreach ($resources as $r) { if (!$this->acl->hasResource($r)) { $this->acl->addResource($r); } } } } } // Add rules if (isset($config['acl']['rule_providers'])) { $rules = []; foreach ($config['acl']['rule_providers'] as $class => $options) { /** @var \Acl\Provider\Rule\ProviderInterface $ruleProvider */ $ruleProvider = $this->serviceLocator->get($class); $rules = $rules + $ruleProvider->getRules(); } foreach ($rules as $rule) { /** @var \Acl\Entity\Rule $rule */ if ($rule->allow) { $this->acl->allow($rule->obj_id, $rule->resource, $rule->privilege); } else { $this->acl->deny($rule->obj_id, $rule->resource, $rule->privilege); } } } $this->loaded = true; } }
public function fillResources(array $resourcesConfig) { foreach ($resourcesConfig as $resource => $options) { $inherit = $this->getOption($options, self::INHERIT); if (null !== $inherit && !is_string($inherit) && !$inherit instanceof ResourceInterface) { throw new Exceptions\RuntimeException('Inherit option must be a string or implement ResourceInterface for resources'); } $this->acl->addResource($resource, $inherit); $privileges = $this->getOption($options, self::PRIVILEGES, []); foreach ($privileges as $role => $actions) { $this->acl->allow([$role], [$resource], $actions); } } }
public function getResourcesACL(\Zend\Permissions\Acl\Acl $acl, \Doctrine\ORM\EntityManager $em) { $repo = $em->getRepository('Security\\Entity\\RecursoSistema'); foreach ($repo->fetchPairs() as $recurso) { $acl->addResource($recurso); } // carrega os recurso desprotegidos foreach ($this->getRecursosDesprotegidos() as $recurso) { if (!$acl->hasResource($recurso)) { $acl->addResource($recurso); } } return $acl; }
/** * Constroi a ACL * @return Acl */ public function build() { // servico de config (array de configuracao) $config = $this->getServiceManager()->get('Config'); $acl = new Acl(); foreach ($config['acl']['roles'] as $role => $parent) { $acl->addRole(new Role($role), $parent); } foreach ($config['acl']['resources'] as $r) { $acl->addResource(new Resource($r)); } foreach ($config['acl']['privilege'] as $role => $privilege) { if (isset($privilege['allow'])) { foreach ($privilege['allow'] as $p) { $acl->allow($role, $p); } } if (isset($privilege['deny'])) { foreach ($privilege['deny'] as $p) { $acl->deny($role, $p); } } } return $acl; }
public function build() { $authService = $this->getServiceLocator()->get('user-service-auth'); $role = $authService->getRole(); $repositoryPerfil = $this->getEm('Admin\\Entity\\Perfil'); $repositoryResource = $this->getEm('Admin\\Entity\\Resource'); $repositoryAcl = $this->getEm('Admin\\Entity\\Acl'); $config = $repositoryAcl->listaAcl(); $config['acl']['roles'] = $repositoryPerfil->getRoles(); $config['acl']['roles']['visitante'] = null; $config['acl']['resources'] = $repositoryResource->getResources(); $acl = new ZendAcl(); foreach ($config['acl']['roles'] as $role => $parent) { $acl->addRole(new GenericRole($role), $parent); } foreach ($config['acl']['resources'] as $resouce) { $acl->addResource(new GenericResource($resouce)); } if (isset($config['acl']['previlege'])) { foreach ($config['acl']['previlege'] as $role => $privilege) { if (isset($privilege['allow'])) { foreach ($privilege['allow'] as $permissao) { $acl->allow($role, $permissao); } } if (isset($privilege['deny'])) { foreach ($privilege['deny'] as $permissao) { $acl->deny($role, $permissao); } } } } return $acl; }
/** * Set and get Zend\Permissions\Acl\Acl * * @see \Contentinum\Service\AclAwareInterface::getAcl() * @return Zend\Permissions\Acl\Acl */ public function getAcl($settings) { if (null === $this->acl) { $acl = new Acl(); // start to set first roles ... foreach ($settings['roles'] as $role) { $parents = null; if (isset($settings['parent'][$role])) { $parents = array($settings['parent'][$role]); } $acl->addRole($role, $parents); } $role = null; // ... then resoures ... foreach ($settings['resources'] as $resource) { $acl->addResource($resource); } // ... and now the rules foreach ($settings['rules'] as $access => $rule) { foreach ($rule as $role => $restrictions) { foreach ($restrictions as $resource => $restriction) { if ('all' == $restriction) { $acl->{$access}($role, $resource); } else { $acl->{$access}($role, $resource, $restriction); } } } } $this->setAcl($acl); } return $this->acl; }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('config.helper')->get('acl'); $acl = new Acl(); foreach ($config['roles'] as $role => $parents) { if (empty($parents)) { $parents = null; } $role = new GenericRole($role); $acl->addRole($role, $parents); } foreach ($config['resources'] as $permission => $controllers) { foreach ($controllers as $controller => $actions) { if (!$acl->hasResource($controller)) { $acl->addResource(new GenericResource($controller)); } foreach ($actions as $action => $role) { if ($action == '*') { $action = null; } if ($permission == 'allow') { $acl->allow($role, $controller, $action); } elseif ($permission == 'deny') { $acl->deny($role, $controller, $action); } else { throw new Exception('No valid permission defined: ' . $permission); } } } } if (class_exists('Zend\\View\\Helper\\Navigation')) { Navigation::setDefaultAcl($acl); } return $acl; }
/** * Constroi a ACL de acordo com as entities * @see Core\Entity\System\Roles * @todo Inclusao das ACLS no Cache * @return Acl */ public function build() { $em = $this->getServiceManager()->get('Doctrine\\ORM\\EntityManager'); $roles = $em->getRepository('Core\\Entity\\System\\Roles')->findAll(); $resources = $em->getRepository('Core\\Entity\\System\\Resources')->findAll(); $acl = new Acl(); foreach ($roles as $role) { $acl->addRole(new Role($role->getRoleName()), $role->getRoleParent()); } foreach ($resources as $r) { $acl->addResource(new Resource($r->getResourceName())); } foreach ($roles as $role) { $rolename = $role->getRoleName(); $allowed = $em->getRepository('Core\\Entity\\System\\Permissions')->findBy(array('idRole' => $role->getId(), 'permission' => 'allow')); foreach ($allowed as $allow) { $resources = $em->getRepository('Core\\Entity\\System\\Resources')->find($allow->getIdResource()); $acl->allow($rolename, $resources->getResourceName()); } $denyed = $em->getRepository('Core\\Entity\\System\\Permissions')->findBy(array('idRole' => $role->getId(), 'permission' => 'deny')); foreach ($denyed as $deny) { $resources = $em->getRepository('Core\\Entity\\System\\Resources')->find($deny->getIdResource()); $acl->deny($rolename, $resources->getResourceName()); } } return $acl; }
/** * @group 4226 */ public function testAllowNullPermissionAfterResourcesExistShouldAllowAllPermissionsForRole() { $this->_acl->addRole('admin'); $this->_acl->addResource('newsletter'); $this->_acl->allow('admin'); $this->assertTrue($this->_acl->isAllowed('admin')); }
/** * getAcl - This cannot be called before resources are parsed * * @param string $resourceId resourceId * @param string $providerId @deprecated No Longer Required - providerId * * @return Acl */ public function getAcl($resourceId, $providerId) { if (!isset($this->acl)) { $this->buildAcl(); } /* resources privileges we load the every time so they maybe updated dynamically */ $resources = $this->getResources($resourceId, $providerId); foreach ($resources as $resource) { if (!$this->acl->hasResource($resource)) { $this->acl->addResource($resource, $resource->getParentResource()); } $privileges = $resource->getPrivileges(); if (!empty($privileges)) { foreach ($privileges as $privilege) { if (!$this->acl->hasResource($privilege)) { $this->acl->addResource($privilege, $resource); } } } } // get only for resources $rules = $this->getRules($resources); /** @var AclRule $aclRule */ foreach ($rules as $aclRule) { if ($aclRule->getRule() == AclRule::RULE_ALLOW) { $this->acl->allow($aclRule->getRoleId(), $aclRule->getResourceId(), $aclRule->getPrivileges(), $aclRule->getAssertion()); } elseif ($aclRule->getRule() == AclRule::RULE_DENY) { $this->acl->deny($aclRule->getRoleId(), $aclRule->getResourceId(), $aclRule->getPrivileges(), $aclRule->getAssertion()); } } return $this->acl; }
/** * autentica o usuário */ public function autenticaAction() { if ($this->getRequest()->isPost()) { $this->adapter->setOptions(array('object_manager' => Conn::getConn(), 'identity_class' => 'MyClasses\\Entities\\AclUsuario', 'identity_property' => 'login', 'credential_property' => 'senha')); $this->adapter->setIdentityValue($this->getRequest()->getPost('login')); $this->adapter->setCredentialValue(sha1($this->getRequest()->getPost('senha'))); $result = $this->auth->authenticate($this->adapter); if ($result->isValid()) { $equipes = $result->getIdentity()->getEquipes(); $acl = new Acl(); $acl->addRole(new Role($equipes[0]->getPerfil())); $recursos = $equipes[0]->getRecursos(); foreach ($recursos as $recurso) { if (!$acl->hasResource($recurso->getRecurso())) { /* echo "add recurso: ". $perfil->getPerfil().", ". $recurso->getRecurso()->getRecurso().", ". $recurso->getPermissao(); */ $acl->addResource(new Resource($recurso->getRecurso())); $acl->allow($equipes[0]->getPerfil(), $recurso->getRecurso()); } } $this->auth->getStorage()->write(array($result->getIdentity(), $equipes[0]->getPerfil(), $acl)); $this->layout()->id = $result->getIdentity()->getId(); $this->layout()->nome = $result->getIdentity()->getNome(); return new ViewModel(array('nome' => $result->getIdentity()->getNome())); } else { return new ViewModel(array('erro' => array_pop($result->getMessages()))); } } }
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { /* @var $aclCache \Zend\Cache\Storage\StorageInterface */ $aclCache = $container->get('AclCache'); $acl = $aclCache->getItem('Acl'); if (!$acl) { /* @var $userApi UserApiInterface */ $userApi = $container->get(UserApiInterface::SERVICE_NAME); $acl = new Acl(); $resources = $userApi->getPermissions(); foreach ($resources as $resource) { $acl->addResource($resource); } $roles = $userApi->getRolesAndParent(); foreach ($roles as $role => $parents) { $this->addRoleToAcl($role, $roles, $acl); } $rolePermissions = $userApi->getRolePermissions(); foreach ($rolePermissions as $role => $permissions) { $acl->allow($role, $permissions); } $deniedRolePermissions = $userApi->getDeniedRolePermissions(); foreach ($deniedRolePermissions as $role => $permissions) { $acl->deny($role, $permissions); } $aclCache->setItem('Acl', $acl); } return $acl; }
/** * @param Acl $acl * @param $resource */ protected function addAclResource(ZendAcl $acl, AclResource $resource) { if (!$acl->hasResource($resource->getResource())) { $acl->addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource->getResource())); } return $this; }
public function createService(ServiceLocatorInterface $serviceLocator) { //print_r('--factoryservicerolecreater'); $config = $serviceLocator->get('config'); $acl = new Acl(); $moduleManager = $serviceLocator->get('ModuleManager'); $modules = $moduleManager->getLoadedModules(); $loadedModules = array_keys($modules); //print_r($loadedModules); if (!empty($loadedModules)) { foreach ($loadedModules as $key) { $acl->addResource(strtolower(trim($key))); } } if (isset($config['ACL_pages'])) { if (!empty($config['ACL_pages'])) { $aclArr = $config['ACL_pages']; foreach ($aclArr as $key => $value) { $parent = null; if (isset($value['parent'])) { $parent = $value['parent']; } if (isset($parent)) { $acl->addRole(new Role($key), $parent); } else { $acl->addRole(new Role($key)); } if (isset($value['action'])) { foreach ($value['action'] as $action => $actArr) { foreach ($actArr as $index) { $acl->allow($key, $action, $index); } } //print_r($value['action']); } //print_r('--key-->'.$key.'--parent-->'.$parent); $parent = null; } } } /*$acl->addRole(new Role('Consultant')) ->addRole(new Role('Supervisor'), 'Consultant') ->addRole(new Role('Admin'), 'Supervisor') ->addRole(new Role('Guest')) ->addRole(new Role('New User'), 'Guest') ->addRole(new Role('Firm User'), 'New User') ->addRole(new Role('Firm Owner'), 'Firm User');*/ /*$acl->addResource('consultant'); $acl->addResource('login'); $acl->addResource('sanalfabrika');*/ /*$acl->allow('consultant', 'sfdm', 'index'); $acl->allow('consultant', 'sfdm', 'registration'); $acl->allow('consultant', 'login', 'index'); */ /*$acl->allow('anonymous', 'album', 'album:add'); $acl->deny('anonymous', 'album', 'album:hello'); $acl->allow('anonymous', 'album', 'album:view'); $acl->allow('anonymous', 'album', 'album:edit'); */ return $acl; }
/** * Create the service using the configuration from the modules config-file * * @param ServiceLocator $services The ServiceLocator * * @see \Zend\ServiceManager\FactoryInterface::createService() * @return Hybrid_Auth */ public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('config'); $config = $config['acl']; if (!isset($config['roles']) || !isset($config['resources'])) { throw new \Exception('Invalid ACL Config found'); } $roles = $config['roles']; if (!isset($roles[self::DEFAULT_ROLE])) { $roles[self::DEFAULT_ROLE] = ''; } $this->admins = $config['admins']; if (!isset($this->admins)) { throw new \UnexpectedValueException('No admin-user set'); } $acl = new Acl(); foreach ($roles as $name => $parent) { if (!$acl->hasRole($name)) { if (empty($parent)) { $parent = array(); } else { $parent = explode(',', $parent); } $acl->addRole(new Role($name), $parent); } } foreach ($config['resources'] as $permission => $controllers) { foreach ($controllers as $controller => $actions) { if ($controller == 'all') { $controller = null; } else { if (!$acl->hasResource($controller)) { $acl->addResource(new Resource($controller)); } } foreach ($actions as $action => $role) { if ($action == 'all') { $action = null; } $assert = null; if (is_array($role)) { $assert = $serviceLocator->get($role['assert']); $role = $role['role']; } $role = explode(',', $role); foreach ($role as $roleItem) { if ($permission == 'allow') { $acl->allow($roleItem, $controller, $action, $assert); } elseif ($permission == 'deny') { $acl->deny($roleItem, $controller, $action, $assert); } else { continue; } } } } } return $acl; }
private function addResources(Acl $acl) { foreach ($this->modules as $module) { if (!$acl->hasResource($module)) { $acl->addResource(strtolower($module)); } } }
public function setupAcl(MvcEvent $e) { $acl = new Acl(); $rolInvitado = new Role('invitado'); $admin = new Admin(); $rolAdmin = new Role($admin->getRol()); $acl->addRole($rolInvitado); $acl->addRole($rolAdmin, $rolInvitado); //el admin hereda los permisos de invitado $acl->addResource('index_empleado'); $acl->addResource('login'); $acl->deny($rolInvitado, 'index_empleado'); $acl->allow($rolInvitado, 'login'); //$acl->allow($rolAdmin, 'login'); $acl->allow($rolAdmin, 'index_empleado'); $vista = $e->getApplication()->getMvcEvent()->getViewModel(); $vista->acl = $acl; $this->acl = $acl; }
private function getConfiguredAcl() { $acl = new Acl(); $acl->addRole(new Role('guest')); $acl->addRole(new Role('member'), 'guest'); $acl->addRole(new Role('admin')); $acl->addResource('/'); $acl->addResource('/login'); $acl->addResource('/member'); $acl->addResource('/member/photo/:id'); $acl->addResource('/admin'); $acl->allow('guest', '/'); $acl->allow('guest', '/login', array('GET', 'POST')); $acl->deny('guest', '/admin'); $acl->allow('member', '/member'); $acl->allow('member', '/member/photo/:id', 'DELETE'); // admin gets everything $acl->allow('admin'); return $acl; }
public function __construct() { // 添加初始化事件函数 $eventManager = $this->getEventManager(); $serviceLocator = $this->getServiceLocator(); $eventManager->attach(MvcEvent::EVENT_DISPATCH, function ($event) use($eventManager, $serviceLocator) { // 权限控制 $namespace = $this->params('__NAMESPACE__'); $controller = $this->params('controller'); $action = $this->params('action'); if ($namespace == 'Idatabase\\Controller' && php_sapi_name() !== 'cli') { // 身份验证不通过的情况下,执行以下操作 if (!isset($_SESSION['account'])) { $event->stopPropagation(true); $event->setViewModel($this->msg(false, '未通过身份验证')); } // 授权登录后,检查是否有权限访问指定资源 $role = isset($_SESSION['account']['role']) ? $_SESSION['account']['role'] : false; $resources = isset($_SESSION['account']['resources']) ? $_SESSION['account']['resources'] : array(); $action = $this->getMethodFromAction($action); $currentResource = $controller . 'Controller\\' . $action; if ($role && $role !== 'root') { $acl = new Acl(); $acl->addRole(new Role($role)); foreach ($resources as $resource) { $acl->addResource(new Resource($resource)); $acl->allow($role, $resource); } $isAllowed = false; try { if ($acl->isAllowed($role, $currentResource) === true) { $isAllowed = true; } } catch (InvalidArgumentException $e) { } if (!$isAllowed) { $event->stopPropagation(true); $event->setViewModel($this->deny()); } } } $this->preDispatch(); if (method_exists($this, 'init')) { try { $this->init(); } catch (\Exception $e) { $event->stopPropagation(true); $event->setViewModel($this->deny($e->getMessage())); } } }, 200); }
/** */ private function initAcl() { if (!is_null($this->acl)) { return; } $this->acl = new Acl(); $config = $this->getServiceLocator()->get('Config'); $roles = $config['acl']['roles']; $allResources = array(); foreach ($roles as $role => $resources) { $role = new GenericRole($role); $this->acl->addRole($role); $allResources = array_merge($resources, $allResources); foreach ($resources as $resource) { if (!$this->acl->hasResource($resource)) { $this->acl->addResource(new GenericResource($resource)); } } foreach ($allResources as $resource) { $this->acl->allow($role, $resource); } } }