/**
  * @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;
 }
Exemplo n.º 2
0
 /**
  * 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);
         }
     }
 }
Exemplo n.º 3
0
 private function addAllowAndDeny(Acl $acl)
 {
     foreach ($this->config as $roleName => $roleConfig) {
         $allowList = isset($roleConfig['allow']) ? $roleConfig['allow'] : [];
         foreach ($allowList as $resource => $privilegeList) {
             if (empty($privilegeList)) {
                 $acl->allow($roleName, strtolower($resource));
             } else {
                 foreach ((array) $privilegeList as $privilege) {
                     $acl->allow($roleName, strtolower($resource), strtolower($privilege));
                 }
             }
         }
         $denyList = isset($roleConfig['deny']) ? $roleConfig['deny'] : [];
         foreach ($denyList as $resource => $privilegeList) {
             if (empty($privilegeList)) {
                 $acl->deny($roleName, strtolower($resource));
             } else {
                 foreach ((array) $privilegeList as $privilege) {
                     $acl->deny($roleName, strtolower($resource), strtolower($privilege));
                 }
             }
         }
     }
 }
Exemplo n.º 4
0
 /**
  * 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);
             }
         }
     }
 }
Exemplo n.º 5
0
 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();
     }
     */
 }
Exemplo n.º 6
0
 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();
     }
 }
Exemplo n.º 7
0
 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);
     }
 }
Exemplo n.º 8
0
 public function getAcl()
 {
     if (!$this->acl) {
         $acl = new Acl();
         $roleGuest = new Role('guest');
         $acl->addRole($roleGuest);
         $acl->addRole(new Role('admin'), $roleGuest);
         $acl->allow($roleGuest, null, 'view');
         $acl->allow('admin', null, array('add', 'edit', 'delete'));
         $this->acl = $acl;
     }
     return $this->acl;
 }
Exemplo n.º 9
0
 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);
         }
     }
 }
Exemplo n.º 10
0
 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;
 }
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
0
 /**
  * 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;
 }
Exemplo n.º 13
0
 /**
  * @group 4226
  */
 public function testAllowNullPermissionAfterResourcesExistShouldAllowAllPermissionsForRole()
 {
     $this->_acl->addRole('admin');
     $this->_acl->addResource('newsletter');
     $this->_acl->allow('admin');
     $this->assertTrue($this->_acl->isAllowed('admin'));
 }
Exemplo n.º 14
0
 /**
  * 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;
 }
Exemplo n.º 15
0
 /**
  * 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())));
         }
     }
 }
Exemplo n.º 16
0
 public function loadPrivilege()
 {
     if (!$this->acl || !$this->acl instanceof \Zend\Permissions\Acl\Acl) {
         return null;
     }
     $userService = $this->getServiceLocator()->get('User\\Service\\User');
     /*@var $userService \User\Service\User */
     if (!$userService->hasIdentity()) {
         return null;
     }
     $user = $userService->getUser();
     if (in_array($user->getRole(), [\User\Model\User::ROLE_ADMIN, \User\Model\User::ROLE_SUPERADMIN, \User\Model\User::ROLE_GUEST])) {
         return null;
     }
     $dependence = $this->acl->getDependencies();
     $resources = null;
     if ($resources) {
         foreach ($resources as $resource) {
             if ($this->acl->hasResource($resource['resource'])) {
                 $this->acl->allow($user->getRole(), $resource['resource'], $resource['privilege']);
                 if (isset($dependence['/' . str_replace(':', '/', $resource['resource']) . '/' . $resource['privilege']])) {
                     foreach ($dependence['/' . str_replace(':', '/', $resource['resource']) . '/' . $resource['privilege']] as $depen) {
                         $arr = explode('/', $depen);
                         if (count($arr) == 4) {
                             if ($this->acl->hasResource($arr[1] . ':' . $arr[2])) {
                                 $this->acl->allow($user->getRole(), $arr[1] . ':' . $arr[2], $arr[3]);
                             }
                         }
                     }
                 }
             }
         }
     }
     return $this->acl;
 }
Exemplo n.º 17
0
 /**
  * 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 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;
 }
 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;
 }
 /**
  * Returns CommentController instance.
  *
  * @param ServiceLocatorInterface $serviceLocator
  * @return CommentController
  **/
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /* @var $serviceLocator Zend\Mvc\Controller\ControllerManager */
     $sm = $serviceLocator->getServiceLocator();
     $em = $sm->get('em');
     $service = new CommentService($em);
     $controller = new CommentController();
     $controller->setEntityManager($em);
     $controller->setService($service);
     $acl = new Acl();
     $acl->addRole(new Role(UserService::ROLE_GUEST));
     $acl->addRole(new Role(UserService::ROLE_ADMIN));
     $acl->addResource($controller);
     $acl->allow(UserService::ROLE_ADMIN, $controller);
     $acl->allow(UserService::ROLE_GUEST, $controller, array('add'));
     $controller->setAcl($acl);
     return $controller;
 }
Exemplo n.º 21
0
 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;
 }
Exemplo n.º 22
0
 public function getPermissosAclRecursoDesprotegidos(\Zend\Permissions\Acl\Acl $acl, \Doctrine\ORM\EntityManager $em)
 {
     $repo = $em->getRepository('Security\\Entity\\Grupo');
     foreach ($repo->fetchPairs() as $grupo) {
         foreach ($this->getRecursosDesprotegidos() as $recurso) {
             $acl->allow($grupo, $recurso);
         }
     }
     return $acl;
 }
Exemplo n.º 23
0
 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);
 }
Exemplo n.º 24
0
 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;
     }
 }
Exemplo n.º 25
0
 public function onInit(MvcEvent $e)
 {
     $routerMatch = $e->getRouteMatch();
     $arrayController = explode("\\", $routerMatch->getParam("controller"));
     $module = strtolower($arrayController[0]);
     $viewModel = $e->getViewModel();
     $this->_mainParam['module'] = strtolower($arrayController[0]);
     $this->_mainParam['controller'] = strtolower($arrayController[2]);
     $this->_mainParam['action'] = strtolower($routerMatch->getParam("action"));
     //truyền ra cho layout
     $viewModel->params = array("module" => strtolower($arrayController[0]), "controller" => strtolower($arrayController[2]), "action" => strtolower($routerMatch->getParam("action")));
     $config = $this->getServiceLocator()->get("config");
     $layout = $config["module_for_layouts"][strtolower($arrayController[0])];
     //set layout
     $this->layout($layout);
     $infoObj = new \ZendVN\System\Info();
     //KIEM TRA USER AuTH
     if ($this->_mainParam['module'] == 'admin') {
         //chưa đăng nhập
         if (!$this->identity()) {
             return $this->redirect()->toRoute('homeShop');
         } else {
             //đăng nhập rồi mà không có quyền vào
             $group_acp = $infoObj->getGroupInfo('group_acp');
             if ($group_acp != 1) {
                 return $this->redirect()->toRoute('homeShop');
             } else {
                 // KIEM TRA PERMISSION
                 $aclObj = new Acl();
                 $role = $infoObj->getPermissionInfo()['role'];
                 $privilegesOfRole = $infoObj->getPermissionInfo()['privileges'];
                 $aclObj->addRole($role);
                 $aclObj->allow($role, null, $privilegesOfRole);
                 $privilegesOfArea = $this->_mainParam['module'] . "|" . $this->_mainParam['controller'] . "|" . $this->_mainParam['action'];
                 if ($aclObj->isAllowed($role, null, $privilegesOfArea) == false) {
                     return $this->goNoAccess();
                 }
             }
         }
     }
     //kiem tra controller user khong đăng nhập thi không được vào
     if ($this->_mainParam['controller'] == 'user' && $this->_mainParam['module'] == 'shop') {
         //chưa đăng nhập
         if (!$this->identity()) {
             return $this->redirect()->toRoute('homeShop');
         }
     }
     // ------------------------------------------------------------
     //func Init() giúp cho các controller extends có thể override onInit()
     $this->init();
 }
Exemplo n.º 26
0
 /**
  */
 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);
         }
     }
 }
Exemplo n.º 27
0
 public function doAuthorization()
 {
     //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('Backend'));
     $acl->addResource(new Resource('Login'));
     $acl->deny('anonymous', 'Backend', 'view');
     $acl->allow('anonymous', 'Login', 'view');
     $acl->allow('user', array('Backend'), array('view'));
     //admin is child of user, can publish, edit, and view too !
     $acl->allow('admin', array('Backend'), array('publish', 'edit'));
     $controller = $this->getController();
     $controllerClass = get_class($controller);
     $namespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
     $role = !$this->getSessContainer()->role ? 'anonymous' : $this->getSessContainer()->role;
     if (!$acl->isAllowed($role, $namespace, 'view') && $controllerClass !== $namespace . "\\Controller\\LoginController") {
         //            $redirector = $controller->getPluginManager()->get('Redirect');
         //            return $redirector->toRoute('backend_logout');
     }
 }
 public function onBootstrap(MvcEvent $event)
 {
     $app = $event->getApplication();
     $sm = $app->getServiceManager();
     $em = $app->getEventManager();
     $cfg = $sm->get('Config');
     if (isset($cfg['deit_authorisation'])) {
         //get the service config
         $serviceCfg = $cfg['deit_authorisation'];
         //construct the Access Control List
         $acl = new Acl();
         if (isset($serviceCfg['acl']['roles'])) {
             foreach ($serviceCfg['acl']['roles'] as $key => $value) {
                 if (is_string($key)) {
                     $acl->addRole($key, $value);
                 } else {
                     $acl->addRole($value);
                 }
             }
         }
         if (isset($serviceCfg['acl']['resources'])) {
             foreach ($serviceCfg['acl']['resources'] as $resource) {
                 $acl->addResource($resource);
             }
         }
         if (isset($serviceCfg['acl']['rules']['allow'])) {
             foreach ($serviceCfg['acl']['rules']['allow'] as $resource => $role) {
                 $acl->allow($role, $resource);
             }
         }
         //create the authorisation service
         $service = new \DeitAuthorisationModule\Service();
         $service->setAcl($acl);
         if (isset($serviceCfg['default_role'])) {
             $service->setDefaultRole($serviceCfg['default_role']);
         }
         if (isset($serviceCfg['role_resolver'])) {
             $service->setRoleResolver($serviceCfg['role_resolver']);
         }
         //create the authorisation strategy
         $options = $sm->get('deit_authorisation_options');
         $strategy = $sm->get($options->getStrategy());
         //attach the service listeners
         $em->attachAggregate($strategy);
         $em->attachAggregate($service);
         //TODO: specify the view
     }
 }
Exemplo n.º 29
0
 /**
  * Constroi a ACL
  * @return Acl 
  */
 public function build()
 {
     $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) {
         foreach ($privilege['allow'] as $p) {
             $acl->allow($role, $p);
         }
         /*foreach ($privilege['deny'] as $p) {
               $acl->deny($role, $p);
           }*/
     }
     return $acl;
 }
Exemplo n.º 30
0
 public function indexAction()
 {
     $mainLayout = $this->initializeAdminArea();
     $lang = $this->params()->fromRoute('lang');
     $id = $this->params()->fromRoute('id');
     $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
     try {
         $helper = new UsersRolesControllerHelper();
         $roleRecord = $helper->recoverWrapperRecordsById(new UsersRolesGetterWrapper(new UsersRolesGetter($em)), array('id' => $id, 'limit' => 1), $id);
         $permissionsWrapper = $helper->recoverWrapper(new UsersRolesPermissionsGetterWrapper(new UsersRolesPermissionsGetter($em)), array());
         $allPermissionsRecords = $permissionsWrapper->getRecords();
         $helper->checkRecords($allPermissionsRecords, 'Permessi utente non presenti in archivio');
         $acl = new Acl();
         $form = new UsersRolesForm();
         if (!empty($roleRecord)) {
             $acl->addRole($roleRecord[0]['name']);
             $currentRolesPermissionsRecords = $helper->recoverWrapperRecords(new UsersRolesPermissionsRelationsGetterWrapper(new UsersRolesPermissionsRelationsGetter($em)), array('roleId' => $roleRecord[0]['id'], 'orderBy' => 'permission.position'));
             if (!empty($currentRolesPermissionsRecords)) {
                 $permissions = array();
                 foreach ($currentRolesPermissionsRecords as $permission) {
                     $permissions[$permission['flag']] = $permission['permissionId'];
                     $acl->addResource($permission['flag']);
                     $acl->allow($roleRecord[0]['name'], $permission['flag']);
                 }
                 $roleRecord[0]['permissions'] = $permissions;
             }
             $formAction = $this->url()->fromRoute('admin/users-roles-update', array('lang' => $lang));
             $formTitle = 'Modifica ruolo utente';
             $formDescription = 'Modifica dati relativi al ruolo';
             $form->setData($roleRecord[0]);
         } else {
             $formTitle = 'Nuovo ruolo utente';
             $formDescription = 'Creazione nuovo ruolo utente';
             $formAction = $this->url()->fromRoute('admin/users-roles-insert', array('lang' => $lang));
         }
         $this->layout()->setVariables(array('form' => $form, 'formAction' => $formAction, 'formTitle' => $formTitle, 'formDescription' => $formDescription, 'roleName' => isset($roleRecord[0]['name']) ? $roleRecord[0]['name'] : null, 'roleId' => isset($roleRecord[0]['id']) ? $roleRecord[0]['id'] : null, 'permissions' => $permissionsWrapper->sortPerGroup($allPermissionsRecords), 'acl' => $acl, 'formDataCommonPath' => 'backend/templates/common/', 'adminAccess' => isset($roleRecord[0]['adminAccess']) ? $roleRecord[0]['adminAccess'] : null, 'formBreadCrumbTitle' => 'Modifica', 'formBreadCrumbCategory' => array(array('label' => 'Utenti', 'href' => $this->url()->fromRoute('admin/users-summary', array('lang' => $lang)), 'title' => 'Elenco utenti'), array('label' => 'Ruoli', 'href' => $this->url()->fromRoute('admin/users-roles-summary', array('lang' => $lang)), 'title' => 'Elenco ruoli')), 'showRolePermissionsTemplate' => 1, 'templatePartial' => self::formTemplate));
     } catch (\Exception $e) {
     }
     $this->layout()->setTemplate($mainLayout);
 }