Example #1
0
 /**
  * Checks if the current user has the priviledge to do something.
  *
  * @param string $priviledge
  * @return AccessProhibitedException
  **/
 protected function _checkAcl($priviledge)
 {
     $service = new UserService($this->_em);
     if (!$this->_acl->isAllowed($service->getCurrentRole(), $this, $priviledge)) {
         throw new AccessProhibitedException('Access is prohibited.');
     }
 }
Example #2
0
 /**
  * Check the acl
  *
  * @param string $resource
  * @param string $privilege
  * @return boolean
  */
 public function isAllowed($resource = null, $privilege = null)
 {
     if (null === $this->acl) {
         $this->getAcl();
     }
     return $this->acl->isAllowed($this->getIdentity()->getRoleId(), $resource, $privilege);
 }
 public function testBuildItemWillAddRulesToAcl()
 {
     $this->assertFalse($this->acl->isAllowed('guest', 'login'));
     $this->assertFalse($this->acl->isAllowed('user', null, 'GET'));
     $this->assertTrue($this->object->buildItem());
     $this->assertTrue($this->acl->isAllowed('guest', 'login'));
     $this->assertTrue($this->acl->isAllowed('user', null, 'GET'));
 }
Example #4
0
 /**
  * @param \Zend\Permissions\Acl\Resource\ResourceInterface|string $resource
  * @param string $action
  * @return bool
  */
 public function can($resource, $action)
 {
     foreach ($this->roles as $role) {
         if ($this->acl->isAllowed($role, $resource, $action)) {
             return true;
         }
     }
     return false;
 }
 public function testBuildCanAcceptXMLAsString()
 {
     $content = file_get_contents(__DIR__ . '/fixtures/test.xml');
     $this->object = new AclBuilder(new StringType($content), $this->acl);
     $this->assertTrue($this->object->build());
     $this->assertTrue($this->acl->hasRole('guest'));
     $this->assertTrue($this->acl->hasResource('logout'));
     $this->assertTrue($this->acl->isAllowed('guest', 'login'));
     $this->assertTrue($this->acl->isAllowed('user', null, 'GET'));
 }
 /**
  * Run the request filter.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle(Request $request, Closure $next, $resource = null, $permission = null)
 {
     if ($this->auth->guest()) {
         if (!$this->acl->isAllowed('guest', $resource, $permission)) {
             return $this->notAllowed($request);
         }
     } elseif (!$this->acl->isAllowed($this->auth->user(), $resource, $permission)) {
         return $this->notAllowed($request);
     }
     return $next($request);
 }
Example #7
0
 /**
  * Check is the user is allowed to the resource on the privilege
  * 
  * @param string $resource
  * @param string $privilege
  * @return bool
  */
 public function isAllowed($user, $resource, $privilege)
 {
     //Get user roles
     $roles = $user->getRoles();
     //Check each role if one of them was allowed
     foreach ($roles as $role) {
         if ($this->acl->isAllowed($role, $resource, $privilege)) {
             return true;
         }
     }
     return false;
 }
Example #8
0
 /**
  *
  * @param string $name            
  * @param string $routename            
  * @return boolean
  */
 public function checkAutorisation($name, $routename)
 {
     $this->initAcl();
     $config = $this->getServiceLocator()->get('Config');
     $filePath = $config['auth']['filePath'];
     $reader = new Ini();
     try {
         $usersData = $reader->fromFile($filePath);
     } catch (\Exception $e) {
         error_log($e->getMessage());
         return false;
     }
     return is_array($usersData) && array_key_exists($name, $usersData) && $this->acl->hasResource($routename) && $this->acl->hasRole($usersData[$name]) && $this->acl->isAllowed($usersData[$name], $routename);
 }
Example #9
0
 /**
  * @group 4226
  */
 public function testAllowNullPermissionAfterResourcesExistShouldAllowAllPermissionsForRole()
 {
     $this->_acl->addRole('admin');
     $this->_acl->addResource('newsletter');
     $this->_acl->allow('admin');
     $this->assertTrue($this->_acl->isAllowed('admin'));
 }
Example #10
0
 /**
  * Check if ACL is Authorized
  *
  * @return Ambigous <boolean, NULL>
  */
 public function isAuthorized()
 {
     // Get current Role, Resource & Privilege
     $role = $this->getAdapter()->getRole();
     $resource = $this->getAdapter()->getResource();
     $privilege = $this->getAdapter()->getPrivilege();
     // if resource is defined in ACL resource
     if ($this->hasResource($resource)) {
         // If role is not define in ACL, we return an exception
         if (!$this->hasRole($role)) {
             throw new Exception\RoleNotDefinedException($role);
         }
         $rules = $this->getAdapter()->getRules();
         // If the resource is defined in resources list but dont have rules, we generate exception
         if (isset($rules['allow'])) {
             $resourcesDefinedInRules = array_keys($rules['allow']);
         }
         if (!in_array($resource, $resourcesDefinedInRules)) {
             throw new Exception\ResourceHaveNoAllowRuleException($resource);
         }
         // If the resource dont have allow rule the resource, we dont authorize
         $privilegesDefinedInResource = array_keys($rules['allow'][$resource]);
         if (!in_array($privilege, $privilegesDefinedInResource)) {
             throw new Exception\ResourcePrivilegeHaveNoAllowRuleException($resource, $privilege);
         }
         // Check if trio role, resource & privilege allowed
         $isAuthorized = parent::isAllowed($role, $resource, $privilege);
         if ($isAuthorized) {
             return true;
         } else {
             throw new Exception\AccessNotAllowedException();
         }
     }
     return true;
 }
Example #11
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);
     }
 }
Example #12
0
 /**
  * @param string|ResourceInterface $resource
  * @param string                   $privilege
  *
  * @return bool
  */
 public function isAllowed($resource, $privilege = null)
 {
     $this->loaded && $this->loaded->__invoke();
     try {
         return $this->acl->isAllowed($this->getIdentity(), $resource, $privilege);
     } catch (InvalidArgumentException $e) {
         return false;
     }
 }
Example #13
0
 /**
  * Function to check permission
  *
  * @param null $resource
  * @param null $privilege
  * @param null $profile
  * @return bool
  */
 public function allows($resource = null, $privilege = null, $profile = null)
 {
     if ($profile === null) {
         $profile = auth('pulsar')->user()->profile_id_010;
     }
     try {
         return parent::isAllowed($profile, $resource, $privilege);
     } catch (Exception\InvalidArgumentException $e) {
         return false;
     }
 }
Example #14
0
 /**
  * check authorized role for specific resources
  * @param MvcEvent $e
  */
 public function authorize(MvcEvent $e)
 {
     $application = $e->getApplication();
     $serviceManger = $application->getServiceManager();
     $authenticationService = $serviceManger->get('Zend\\Authentication\\AuthenticationService');
     $loggedUser = $authenticationService->getIdentity();
     $role = !$loggedUser ? self::DEFAULT_ROLE : $loggedUser->getRole();
     //get current resource
     $routeMatch = $e->getRouteMatch();
     $routeName = $routeMatch->getMatchedRouteName();
     $controller = $routeMatch->getParam('controller', 'not-found');
     $action = $routeMatch->getParam('action');
     $this->acl = $this->setAcl();
     $isAllowed = $this->acl->isAllowed($role, $controller, $action);
     if (!$isAllowed) {
         $response = $e->getResponse();
         $response->setStatusCode(404);
     }
     return $isAllowed;
 }
Example #15
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);
 }
 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();
 }
 public function __construct($roleName, array $permissions, Acl $acl)
 {
     parent::__construct();
     $this->setAttribute('method', 'post');
     $roles = $acl->getRoles();
     $parentPermissions = [];
     foreach ($roles as $role) {
         if ($acl->inheritsRole($roleName, $role, true)) {
             foreach ($permissions as $permissionId => $permission) {
                 if ($acl->isAllowed($role, $permission)) {
                     $parentPermissions[$permissionId] = $permissionId;
                 }
             }
         }
     }
     $permissionGroups = [];
     foreach ($permissions as $permissionId => $permission) {
         $fragments = explode('/', $permission);
         $groupName = reset($fragments);
         if (!array_key_exists($groupName, $permissionGroups)) {
             $permissionGroups[$groupName] = [];
         }
         $permissionGroups[$groupName][] = $permissionId;
     }
     foreach ($permissionGroups as $groupName => $groupPermissions) {
         foreach ($groupPermissions as $permission) {
             $permissionCheck = new Checkbox($permission);
             $permissionCheck->setLabel($permissions[$permission]);
             if (array_key_exists($permission, $parentPermissions)) {
                 $permissionCheck->setValue(true);
                 $permissionCheck->setAttribute('disabled', true);
             }
             $this->add($permissionCheck);
             if (!array_key_exists($groupName, $this->permissionGroups)) {
                 $this->permissionGroups[$groupName] = [];
             }
             $this->permissionGroups[$groupName][] = $permissionCheck;
         }
     }
     $submit = new Submit('save');
     $submit->setValue('save');
     $submit->setAttribute('class', 'btn btn-primary');
     $this->add($submit);
 }
 /**
  * Override isAllowed function to also support multiple roles
  *
  * @see \Zend\Permissions\Acl\Acl::isAllowed()
  * @param Role\RoleInterface|string|array $role        	
  * @param Resource\ResourceInterface|string $resource        	
  * @param string $privilege        	
  * @return bool
  */
 public function isAllowed($roles = NULL, $resource = NULL, $priviledge = NULL)
 {
     if (true === $this->allow_access_when_resource_unknown && !$this->hasResource($resource)) {
         return true;
     }
     try {
         if (is_array($roles)) {
             foreach ($roles as $role) {
                 if (true === parent::isAllowed($role, $resource, $priviledge)) {
                     return true;
                 }
             }
         } else {
             return parent::isAllowed($roles, $resource, $priviledge);
         }
     } catch (InvalidArgumentException $e) {
         // Role or Resource was not found (maybe not even configured)
         return $this->allow_access_when_resource_unknown === true;
     }
     return false;
 }
Example #19
0
 /**
  * @param  RoleInterface|string|number            $role
  * @param  ResourceInterface|string               $resource
  * @param  string                                 $privilege
  * @return bool
  */
 public function isAllowed($role = null, $resource = null, $privilege = null)
 {
     if (is_null($this->acl)) {
         $this->init();
     }
     if (!is_null($role) && !$role instanceof RoleInterface) {
         $roleEntity = $this->findRole($role);
     } else {
         $roleEntity = $role;
     }
     if (!$this->hasResource($resource)) {
         if ($this->moduleOptions->isPermissive()) {
             $resource = null;
         } else {
             return false;
         }
     }
     if ($this->acl->hasRole($roleEntity) || is_null($roleEntity)) {
         return $this->acl->isAllowed($roleEntity, $resource, $privilege);
     } else {
         return false;
     }
 }
Example #20
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');
     }
 }
Example #21
0
 /**
  * @group ZF-7973
  */
 public function testAclPassesPrivilegeToAssertClass()
 {
     $assertion = new TestAsset\AssertionZF7973();
     $acl = new Acl\Acl();
     $acl->addRole('role');
     $acl->addResource('resource');
     $acl->allow('role', null, null, $assertion);
     $allowed = $acl->isAllowed('role', 'resource', 'privilege', $assertion);
     $this->assertTrue($allowed);
 }
Example #22
0
 public function testOverrideIsAllowed()
 {
     $acl = new Acl();
     $acl->addRole('role1');
     $acl->addResource('resource1');
     $acl->addResource('resource2');
     $acl->allow(null, 'resource1', null);
     $acl->allow(null, 'resource2', 'view');
     $acl->deny('role1', 'resource1', null);
     $service = $this->serviceManager->get('AclService4');
     $service->loadResource(null, null);
     $this->assertSame($acl->isAllowed('role1', 'resource1', 'add'), $service->isAllowed('role1', 'resource1', 'add'));
     $this->assertSame($acl->isAllowed('role1', 'resource2', 'add'), $service->isAllowed('role1', 'resource2', 'add'));
     $this->assertSame($acl->isAllowed('role1', 'resource2', 'view'), $service->isAllowed('role1', 'resource2', 'view'));
 }
 /**
  * @param string $role_id
  * @param string $resource_id
  * @return bool
  */
 public function isAllowed($role_id = '', $resource_id = '')
 {
     return $this->acl->isAllowed($role_id, $resource_id);
 }
 /**
  * Returns true if and only if the Role has access to the Resource
  *
  * @param  Zend\Permissions\Acl\Role\RoleInterface|string           $role
  * @param  Zend\Permissions\Acl\Resource\ResourceInterface|string   $resource
  * @param  string                                                   $privilege
  * @return bool
  */
 public function isAllowed($role = null, $resource = null, $privilege = null)
 {
     if (!$this->hasRole($role)) {
         return false;
     }
     if (!$this->hasResource($resource)) {
         return false;
     }
     return parent::isAllowed($role, $resource, $privilege);
 }
Example #25
0
 public function initAcl(MvcEvent $e)
 {
     $application = $e->getApplication();
     $sm = $application->getServiceManager();
     $acl = new Acl();
     $roles = $sm->get("Application\\Model\\RolesBO");
     $recursos = $sm->get("Application\\Model\\RecursosBO");
     $rolesRecursos = $sm->get("Application\\Model\\RolesRecursosBO");
     $usuarios = $sm->get("Application\\Model\\UsuariosBO");
     // Se listan todos los recursos y se los agrega a la ACL
     foreach ($recursos->obtenerTodos() as $recurso) {
         if (!$acl->hasResource($recurso->getRecursosID())) {
             $genericResource = new GenericResource($recurso->getRecursosID());
             $acl->addResource($genericResource);
         }
     }
     // Se registra el rol en la ACL
     $sesion = new Container("CoreAppSesion");
     if (!$acl->hasRole($sesion->user_rol_id)) {
         $genericRole = new GenericRole($sesion->user_rol_id);
         $acl->addRole($genericRole);
     }
     $services = $application->getServiceManager();
     // obtenemos todos los recuersosque tiene la ACL
     foreach ($acl->getResources() as $resource) {
         // Obtenemos los recursos disponibles para el rol
         foreach ($rolesRecursos->obtenerRecursosPorRol($sesion->user_rol_id) as $recursoAsignado) {
             // Si el recurso asignado es el mismo recurso de la ACL lo permitimos
             if ($resource == $recursoAsignado->getAppRecursosID()) {
                 $acl->allow($genericRole, $acl->getResource($resource));
             }
         }
     }
     // Si el recurso no esta permitido lo denegamos
     foreach ($acl->getResources() as $resource) {
         if (!$acl->isAllowed($genericRole, $acl->getResource($resource))) {
             $acl->deny($genericRole, $acl->getResource($resource));
         }
     }
     $this->acl = $acl;
 }
Example #26
0
 /**
  * Check if a role has privilege to access given resource
  *
  * @param string $role
  * @param string $resource
  * @param string $privilege
  * @return bool
  */
 public function isAllowed($role = null, $resource = null, $privilege = null)
 {
     $this->_load();
     return $this->acl->isAllowed($role, $resource, $privilege);
 }
Example #27
0
 public function index06Action()
 {
     $aclObj = new Acl();
     $aclObj->addRole("member")->addRole("manager", "member")->addRole("admin", "manager");
     //add controller
     //module abc
     $aclObj->addResource("abc:news")->addResource("def:books");
     //it's mean Role member có thể truy cập vào action "info,index" trong controller news
     $aclObj->allow("member", "abc:news", array("info", "index"));
     $aclObj->allow("member", "def:books", array("info", "index", "edit", "add"));
     $role = "member";
     $resource = "def:books";
     $privileges = array("info", "index", "add", "edit", "delete");
     if ($aclObj->hasRole($role)) {
         foreach ($privileges as $privilege) {
             if ($aclObj->isAllowed($role, $resource, $privilege)) {
                 echo sprintf("<h3 style='color:red;font-weight:bold'>%s : Được quyền truy cập %s - %s</h3>", $role, $resource, $privilege);
             } else {
                 echo sprintf("<h3 style='color:red;font-weight:bold'>%s : Không được quyền truy cập %s - %s</h3>", $role, $resource, $privilege);
             }
         }
     }
     return false;
 }
Example #28
0
 /**
  * Authorizes a request. If the authorization fails a 403 response code
  * will be set and the propagation will be stopped
  *
  * @param MvcEvent $e
  * @return void
  */
 public function authorize(MvcEvent $e)
 {
     $routeParams = $e->getRouteMatch()->getParams();
     $controller = isset($routeParams['controller']) ? $routeParams['controller'] : null;
     $action = isset($routeParams['action']) ? $routeParams['action'] : null;
     if (empty($controller) or empty($action)) {
         throw new \Exception('Couldn\'t resolve controller or action');
     }
     $application = $e->getApplication();
     $sm = $application->getServiceManager();
     // Load the configuration
     $config = $sm->get('config');
     if (!isset($config['acl']) or !is_array($config['acl']) or !isset($config['acl']['roles']) or !is_array($config['acl']['roles']) or !isset($config['acl']['resources']) or !is_array($config['acl']['resources']) or !isset($config['acl']['rules']) or !is_array($config['acl']['rules'])) {
         throw new \Exception('ACL\'s are not configured correctly');
     }
     $aclConfig =& $config['acl'];
     $acl = new Acl();
     // Deny as default policy
     $acl->deny();
     // Add the roles
     foreach ($aclConfig['roles'] as $role) {
         $inherit = null;
         if (is_array($role)) {
             $inherit = $role[1];
             $role = $role[0];
         }
         $acl->addRole(new Role($role), $inherit);
     }
     // Add the resources
     foreach ($aclConfig['resources'] as $resource) {
         if (strpos($resource, $this->resourcePrefix . ':') === 0) {
             $acl->addResource(new Resource($resource));
         }
     }
     // Set up the rules
     foreach ($aclConfig['rules'] as $rule) {
         $type = isset($rule[0]) ? $rule[0] : null;
         $role = isset($rule[1]) ? $rule[1] : null;
         $resource = isset($rule[2]) ? $rule[2] : null;
         if (!$type) {
             throw new \Exception('No type defined');
         }
         if (!$role) {
             throw new \Exception('No role defined');
         }
         switch ($type) {
             case 'allow':
                 $acl->allow($role, $resource);
                 break;
             case 'deny':
                 $acl->deny($role, $resource);
                 break;
             default:
                 throw new \Exception('Invalid rule type');
                 break;
         }
     }
     // Set the resource based on the request params
     $resource = 'controller:' . $controller . ':' . $action;
     // Set the users role
     $role = 'guest';
     $identity = $sm->get('ControllerPluginManager')->get('identity');
     if ($user = $identity()) {
         $role = $user->role;
     }
     // Authorize
     try {
         return $acl->isAllowed($role, $resource);
     } catch (\Zend\Permissions\Acl\Exception\InvalidArgumentException $exception) {
         // If the route cannot be matched the router will show a 404 page;
         // everyone can access the 404 page
         $routeMatch = $e->getRouteMatch();
         if (!$routeMatch or !$routeMatch->getMatchedRouteName()) {
             return true;
         }
         // Check if the controller/action exists. If they don't we return
         // true to make sure the 404 page is rendered
         $controllerLoader = $sm->get('ControllerLoader');
         if (!$controllerLoader->has($controller)) {
             return true;
         }
         $controller = $controllerLoader->get($controller);
         $method = $controller::getMethodFromAction($action);
         if (!method_exists($controller, $method)) {
             return true;
         }
         $logger = $sm->get('Logger');
         $logger->debug('Invalid ACL ressource requested: ' . $resource . ' (' . $exception->getMessage() . ')');
         return false;
     }
 }
Example #29
0
 /**
  * @param string $attribute
  * @param ResourceNode $resourceNode
  * @param null $user
  *
  * @return bool
  */
 protected function isGranted($attribute, $resourceNode, $user = null)
 {
     // Make sure there is a user object (i.e. that the user is logged in)
     if (!$user instanceof UserInterface) {
         return false;
     }
     // Checking admin roles
     $authChecker = $this->container->get('security.authorization_checker');
     // Admins have access to everything
     if ($authChecker->isGranted('ROLE_ADMIN')) {
         // return true;
     }
     // Check if I'm the owner
     $creator = $resourceNode->getCreator();
     if ($creator instanceof UserInterface && $user->getUsername() == $creator->getUsername()) {
         //return true;
     }
     // Checking possible links connected to this resource
     $request = $this->container->get('request_stack')->getCurrentRequest();
     $courseCode = $request->get('course');
     $sessionId = $request->get('session');
     $links = $resourceNode->getLinks();
     $linkFound = false;
     /** @var ResourceLink $link */
     foreach ($links as $link) {
         $linkUser = $link->getUser();
         $linkCourse = $link->getCourse();
         $linkSession = $link->getSession();
         $linkUserGroup = $link->getUserGroup();
         // Check if resource was sent to the current user
         if ($linkUser instanceof UserInterface && $linkUser->getUsername() == $creator->getUsername()) {
             $linkFound = true;
             break;
         }
         // @todo Check if resource was sent to a usergroup
         // @todo Check if resource was sent to a group inside a course
         // Check if resource was sent to a course inside a session
         if ($linkSession instanceof Session && !empty($sessionId) && $linkCourse instanceof Course && !empty($courseCode)) {
             $session = $this->container->get('chamilo_core.manager.session')->find($sessionId);
             $course = $this->container->get('chamilo_core.manager.course')->findOneByCode($courseCode);
             if ($session instanceof Session && $course instanceof Course && $linkCourse->getCode() == $course->getCode() && $linkSession->getId() == $session->getId()) {
                 $linkFound = true;
                 break;
             }
         }
         // Check if resource was sent to a course
         if ($linkCourse instanceof Course && !empty($courseCode)) {
             $course = $this->container->get('chamilo_core.manager.course')->findOneByCode($courseCode);
             if ($course instanceof Course && $linkCourse->getCode() == $course->getCode()) {
                 $linkFound = true;
                 break;
             }
         }
     }
     // No link was found!
     if ($linkFound === false) {
         return false;
     }
     // Getting rights from the link
     $rightFromResourceLink = $link->getRights();
     if ($rightFromResourceLink->count()) {
         // Taken rights from the link
         $rights = $rightFromResourceLink;
     } else {
         // Taken the rights from the default tool
         $rights = $link->getResourceNode()->getTool()->getToolResourceRights();
     }
     // Asked mask
     $mask = new MaskBuilder();
     $mask->add($attribute);
     $askedMask = $mask->get();
     // Check all the right this link has.
     $roles = array();
     foreach ($rights as $right) {
         $roles[$right->getMask()] = $right->getRole();
     }
     // Setting zend simple ACL
     $acl = new Acl();
     // Creating roles
     // @todo move this in a service
     $userRole = new Role('ROLE_USER');
     $teacher = new Role(self::ROLE_CURRENT_COURSE_TEACHER);
     $student = new Role(self::ROLE_CURRENT_COURSE_STUDENT);
     $superAdmin = new Role('ROLE_SUPER_ADMIN');
     $admin = new Role('ROLE_ADMIN');
     // Adding roles to the ACL
     // User role
     $acl->addRole($userRole);
     // Adds role student
     $acl->addRole($student);
     // Adds teacher role, inherit student role
     $acl->addRole($teacher, $student);
     $acl->addRole($superAdmin);
     $acl->addRole($admin);
     // Adds a resource
     $resource = new Resource($link);
     $acl->addResource($resource);
     // Role and permissions settings
     // Students can view
     // Student can just view (read)
     $acl->allow($student, null, self::getReaderMask());
     // Teacher can view/edit
     $acl->allow($teacher, null, array(self::getReaderMask(), self::getEditorMask()));
     // Admin can do everything
     $acl->allow($admin);
     $acl->allow($superAdmin);
     foreach ($user->getRoles() as $role) {
         if ($acl->isAllowed($role, $resource, $askedMask)) {
             dump('passed');
             return true;
         }
     }
     dump('not allowed to ' . $attribute);
     return false;
 }
 public function doAuthorization(\Zend\Mvc\MvcEvent $event)
 {
     // Ignore ACL if in console
     if ($event->getRequest() instanceof Request) {
         return;
     }
     $controller = $event->getTarget();
     $controllerClass = get_class($controller);
     $moduleName = substr($controllerClass, 0, strpos($controllerClass, '\\'));
     $routeMatch = $event->getRouteMatch()->getMatchedRouteName();
     $manager = $this->getController()->getServiceLocator()->get('ModuleManager');
     $loadedModules = $manager->getLoadedModules();
     $certigateAclConfig = $loadedModules['CertigateAcl']->getConfig()['roles_management'];
     $excludedModules = $certigateAclConfig['excluded_modules'];
     $anonymousRoutes = $certigateAclConfig['anonymous_routes'];
     $signInController = 'DefaultModule\\Controller\\SignController';
     $router = $event->getRouter();
     // return if the target is in excluded modules
     if (in_array($moduleName, $excludedModules)) {
         return;
     }
     // return if not logged in
     $auth = new AuthenticationService();
     $authenticated = true;
     if (!$auth->hasIdentity()) {
         $authenticated = false;
     }
     // set ACL
     $acl = new ZendAcl();
     $acl->deny();
     // Defining Resources
     foreach ($loadedModules as $k => $v) {
         if (!in_array($k, $excludedModules)) {
             $acl->addResource($k);
         }
     }
     if (count($anonymousRoutes) > 0) {
         $acl->addRole(new ZendRole(Role::ANONYMOUS_ROLE));
         foreach ($anonymousRoutes as $privilege => $anonymousRoute) {
             $acl->allow(Role::ANONYMOUS_ROLE, $anonymousRoute['resource'], $privilege);
         }
     }
     if ($authenticated === true) {
         /* @var $em \Doctrine\ORM\EntityManager */
         $em = $this->getController()->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
         // Roles
         $roles = $em->getRepository('Users\\Entity\\Role')->findAll();
         foreach ($roles as $r) {
             $acl->addRole(new ZendRole($r->getName()));
         }
         // Fetching Privileges
         $privileges = $em->getRepository('Users\\Entity\\Acl')->findAll();
         $allRolesPriveleges = [];
         foreach ($privileges as $p) {
             $allRolesPriveleges[$p->getRole()->getName()][$p->getModule()][] = $p->getRoute();
         }
         // Defining Permissions
         $acl->allow('Admin');
         // allow everything for Admin
         foreach ($allRolesPriveleges as $role => $modules) {
             foreach ($modules as $module => $routes) {
                 foreach ($routes as $r) {
                     $acl->allow($role, $module, $r);
                 }
             }
         }
         // get logged in user roles
         $userRoles = $em->find('\\Users\\Entity\\User', $auth->getIdentity()['id'])->getRoles();
         $isAllowed = false;
         if ($acl->isAllowed(Role::ANONYMOUS_ROLE, $moduleName, $routeMatch)) {
             $isAllowed = true;
         } else {
             foreach ($userRoles as $userRole) {
                 if ($acl->isAllowed($userRole->getName(), $moduleName, $routeMatch)) {
                     $isAllowed = true;
                     break;
                 }
             }
         }
         if ($isAllowed === false) {
             $url = $router->assemble(array(), array('name' => 'noaccess'));
             $status = 302;
         }
     }
     if ($authenticated === false && $controllerClass != $signInController) {
         if (!$acl->isAllowed(Role::ANONYMOUS_ROLE, $moduleName, $routeMatch)) {
             // redirect to sign/in
             $url = $router->assemble(array('action' => 'in'), array('name' => 'defaultSign'));
             $status = 200;
         }
     }
     if (isset($url) && isset($status)) {
         $response = $event->getResponse();
         $response->setStatusCode(302);
         // redirect to login page or other page.
         $response->getHeaders()->addHeaderLine('Location', $url);
         $event->stopPropagation();
     }
 }