/** * This action is executed before execute any action in the application * * @param Event $event * @param Dispatcher $dispatcher * @return bool */ public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher) { $module = $dispatcher->getModuleName(); $controller = $module . ':' . $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $auth = $this->auth->getIdentity(); $role = 'Visitante'; $url = '/' . $module; $name = ''; if (!$auth) { $this->auth->setGuest($name, $role, $url); } else { if ($auth['usuario_tipo'] == 'Visitante' && $action != 'auth') { if ($auth['home'] != $url) { $this->auth->setGuest($name, $role, $url); } } else { $role = $auth['usuario_tipo']; } } $acl = $this->getAcl(); $allowed = $acl->isAllowed($role, $controller, $action); if ($allowed != Acl::ALLOW) { $dispatcher->forward(array('controller' => 'errors', 'action' => 'show401')); return false; } }
/** * This action is executed before execute any action in the application. * * @param PhalconEvent $event Event object. * @param Dispatcher $dispatcher Dispatcher object. * * @return mixed */ public function beforeDispatch(PhEvent $event, Dispatcher $dispatcher) { $di = $this->getDI(); $cookie = $di->getCookie(); $session = $di->getSession(); $config = $di->getConfig(); $languageCode = ''; if ($di->get('app')->isConsole()) { return; } // Detect language from cookie if ($cookie->has('languageCode')) { $languageCode = $cookie->get('languageCode')->getValue(); } else { // Get default language from language model $languageCode = LanguageModel::findFirst(['default = :isdefault: AND status = :enable:', 'bind' => ['isdefault' => LanguageModel::IS_DEFAULT, 'enable' => LanguageModel::STATUS_ENABLE]])->code; } // Set language code to session if ($session->has('languageCode') && $session->get('languageCode') != $languageCode || !$session->has('languageCode')) { $session->set('languageCode', $languageCode); } $messages = []; $directory = $di->get('registry')->directories->modules . ucfirst($dispatcher->getModuleName()) . '/Lang/' . $languageCode . '/' . strtolower($dispatcher->getControllerName()); $extension = '.php'; if (file_exists($directory . $extension)) { require $directory . $extension; } // add default core lang package require $di->get('registry')->directories->modules . self::DEFAULT_LANG_PACK . '/Lang/' . $languageCode . '/default.php'; $translate = new PhTranslateArray(['content' => array_merge($messages, $default)]); $di->set('lang', $translate); return !$event->isStopped(); }
/** * Generate a route based on the current URL. * * @param $path_info * @return string The routed URL. */ public function routeFromHere($path_info) { $new_path = array('module' => $this->_dispatcher->getModuleName(), 'controller' => $this->_dispatcher->getControllerName(), 'action' => $this->_dispatcher->getActionName(), 'params' => (array) $this->_dispatcher->getParams()); if (isset($path_info['module'])) { $new_path['module'] = $path_info['module']; unset($path_info['module']); } if (isset($path_info['controller'])) { $new_path['controller'] = $path_info['controller']; unset($path_info['controller']); } if (isset($path_info['action'])) { $new_path['action'] = $path_info['action']; unset($path_info['action']); } if (count($path_info) > 0) { foreach ((array) $path_info as $param_key => $param_value) { $new_path['params'][$param_key] = $param_value; } } if (isset($new_path['params']['name'])) { // Allow support for named routes. $route_name = $new_path['params']['name']; unset($new_path['params']['name']); return $this->named($route_name, $new_path['params']); } else { return $this->route($new_path); } }
public function __construct(DefaultAcl $acl, Dispatcher $dispatcher) { $role = $this->getRole(); $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $resourceKey = $module . '/' . $controller; $resourceVal = $action; if ($acl->isResource($resourceKey)) { if (!$acl->isAllowed($role, $resourceKey, $resourceVal)) { $this->accessDenied($role, $resourceKey, $resourceVal); } } }
public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $role = $this->getRole(); $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $acl = $this->acl->getAcl(); $resource = $module . '/' . $controller; if ($acl->isResource($resource)) { if (!$acl->isAllowed($role, $resource, $action)) { $this->notPermission($dispatcher); } } else { $this->resourceNotFound($resource); } }
/** * This action is executed before execute any action in the application */ public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $role = $this->getActiveRole(); $allowed = $this->getAcl()->isAllowed($role, $dispatcher->getControllerName(), $dispatcher->getActionName()); if ($allowed != Acl::ALLOW) { $this->flash->error("No Tienes acceso a este Modulo " . $dispatcher->getActionName() . " on " . $dispatcher->getModuleName() . " module"); /* $dispatcher->forward( array( 'controller' => 'index', 'action' => 'index' ) ); */ $dispatcher->setActionName('nonexistaction'); header('location:/401'); } }
public function __construct(Dispatcher $dispatcher, array $modules, $defaultLanguage = 'en') { $this->lang = $dispatcher->getParam('language'); if (is_null($this->lang)) { $this->lang = $defaultLanguage; } $config = $dispatcher->getDI()->get('config'); $translations = $this->getMessages($config->projectPath . 'common/'); if (!is_array($translations)) { $translations = []; } $translationsModule = $this->getMessages($modules[$dispatcher->getModuleName()]); if (!is_array($translationsModule)) { $translationsModule = []; } $translations = array_merge($translations, $translationsModule); $this->translate = new NativeArray(['content' => $translations]); }
/** * This action is executed before execute any action in the application */ public function beforeDispatch(\Phalcon\Events\Event $event, \Phalcon\Mvc\Dispatcher $dispatcher) { // check installation /*if (!$this->_di->get('config')->installed) { $this->_di->set('installationRequired', true); if ($dispatcher->getControllerName() != 'install') { return $dispatcher->forward([ 'module' => 'core', "controller" => "install", "action" => "index" ]); } return; }*/ $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $viewer = $this->_di->get('viewer'); $acl = $this->_di->get('acl'); $registry = $this->_di->get('registry'); $adminModuleName = $registry->adminModule ? $registry->adminModule : 'admin'; // check admin area if ($module == $adminModuleName) { if ($controller == 'admin') { return; } if ($acl->isAllowed($viewer->getRole(), \Engine\Acl\Dispatcher::ACL_ADMIN_MODULE, \Engine\Acl\Dispatcher::ACL_ADMIN_CONTROLLER, '*') || $acl->isAllowed($viewer->getRole(), \Engine\Acl\Dispatcher::ACL_ADMIN_MODULE, \Engine\Acl\Dispatcher::ACL_ADMIN_CONTROLLER, 'read')) { return; } if ($acl->isAllowed($viewer->getRole(), $module, $controller, $action, false)) { return; } if ($this->_di->get('request')->isAjax() == true) { return $dispatcher->forward(["controller" => 'admin', "action" => 'denied']); } else { return $dispatcher->forward(["controller" => 'admin', "action" => 'index']); } } else { if (!$acl->isAllowed($viewer->getRole(), $module, $controller, $action, true)) { return $dispatcher->forward(["controller" => 'error', "action" => 'show404']); } } }
/** * 自动将控制器名称保存到资源表 * @author hxc * */ public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); /* $objResource= new \App\M\Resource(); //自动将控制器名称保存到资源表 $config = DI::getDefault()->getShared('config'); if ($config['is_dev']) { $userData=$this->session->get("userInfo"); $companyId = (int)$userData['companyId']; $actionName=$module.'_'.$controller.'_'.$action; $controllerName=$module.'_'.$controller; $objResource->addResource($companyId,$module,$controllerName,$actionName); } */ }
/** * This action is executed before execute any action in the application * * @param Event $event * @param Dispatcher $dispatcher * @return \Phalcon\Http\ResponseInterface */ public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $config = $this->di->get('config'); $this->auth = $this->session->get('auth'); //Get current resource $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $rule = $module . '|' . $controller . '|' . $action; if ($this->checkPagePublic($rule)) { return true; } else { if ($this->auth) { if (!$this->isAllowed('admin|index|index')) { $this->session->remove('auth'); unset($_SESSION); } if ($this->isAllowed($rule)) { if (time() - $this->auth['last_use_admin'] > $config->auth->lifetime) { //$this->session->remove('auth'); $this->flashSession->warning(__('gb_session_login_timeout')); $this->response->redirect('/admin/user/login/'); return false; } else { $this->auth['last_use_admin'] = time(); $this->session->set('auth', $this->auth); return true; } } else { if ($config->debug) { $this->flashSession->warning(__('gb_permission_denied_for_action', [1 => $this->getRuleError($rule) . ' => ' . $module . '<strong style=\'color: red;\'> | </strong>' . $controller . '<strong style=\'color: red;\'> | </strong>' . $action])); } else { $this->flashSession->warning('gb_permission_denied'); } if ($this->isAllowed('user|profile|index')) { $this->response->redirect($this->urlRedirectNotPermission); } else { $this->response->redirect('/admin/'); } return false; } } else { if ($config->debug) { $this->flashSession->warning(__('gb_permission_denied_for_action', [1 => $this->getRuleError($rule) . ' => ' . $module . '<strong style=\'color: red;\'> | </strong>' . $controller . '<strong style=\'color: red;\'> | </strong>' . $action])); } else { $this->flashSession->warning('gb_permission_denied'); } $this->response->redirect('/admin/user/login/'); return false; } } }
/** * This action is executed before execute any action in the application. * * @param PhalconEvent $event Event object. * @param Dispatcher $dispatcher Dispatcher object. * * @return mixed */ public function beforeDispatch(PhEvent $event, Dispatcher $dispatcher) { $me = null; $config = $this->getDI()->get('config'); $cookie = $this->getDI()->get('cookie'); $session = $this->getDI()->get('session'); // check exsited cookie if ($cookie->has('remember-me')) { $rememberMe = $cookie->get('remember-me'); $userId = $rememberMe->getValue(); $myUser = User::findFirst(['id = :id: AND status = :status:', 'bind' => ['id' => $userId, 'status' => User::STATUS_ENABLE]]); if ($myUser) { } $this->session->set('me', $me); $role = $myUser->role; } else { //Get role name from session if ($session->has('me')) { $me = $session->get('me'); $role = $me->role; } else { $role = ROLE_GUEST; } } $current_resource = $dispatcher->getModuleName() . '/' . strtolower($dispatcher->getControllerName()); $current_action = $dispatcher->getActionName(); $acl = $this->getAcl($config); $allowed = $acl->isAllowed($role, $current_resource, $current_action); if ($allowed != PhAcl::ALLOW) { $this->getDI()->getEventsManager()->fire('dispatch:beforeException', $dispatcher, new Dispatcher\Exception()); } return !$event->isStopped(); }
/** * @param Dispatcher $dispatcher * @return string */ protected function getResourceName(Dispatcher $dispatcher) { $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); return sprintf('mvc:%s:%s', lcfirst($module), str_replace('\\', '-', $controller)); }
/** * * @param Dispatcher $dispatcher */ public function beforeExecuteRoute(Dispatcher $dispatcher) { try { $identity = $this->auth->getIdentity(); $moduleCurrent = $dispatcher->getModuleName(); $controllerCurrent = $dispatcher->getControllerName(); $actionCurrent = $dispatcher->getActionName(); if (is_null($identity)) { if (!$this->access->isAllowed('public', $moduleCurrent, $controllerCurrent, $actionCurrent)) { if ($moduleCurrent . $controllerCurrent . $actionCurrent == 'intranetindexindex') { return $this->response->redirect('login'); } throw new Exception('Sua sessão foi finalizada.'); } } else { if (!$this->access->isAllowed('public', $moduleCurrent, $controllerCurrent, $actionCurrent)) { if (!$this->access->isAllowed('private', $moduleCurrent, $controllerCurrent, $actionCurrent)) { if ($this->access->isAllowed('private', $moduleCurrent, $controllerCurrent, 'index')) { $this->flash->error('Você não tem acesso a ' . $moduleCurrent . '/' . $controllerCurrent . '/' . $actionCurrent); $this->response->redirect($moduleCurrent . '/' . $controllerCurrent . '/index'); } else { if ($this->access->isAllowed('private', 'intranet', 'index', 'index')) { $this->flash->error('Você não tem acesso a ' . $moduleCurrent . '/' . $controllerCurrent); return $this->response->redirect('/'); } else { throw new Exception('Sua sessão foi finalizada.'); } } } } } } catch (Exception $e) { $this->flash->error($e->getMessage()); $this->response->redirect('login'); } }
/** * registering module-specific services * * @param \DiCustom $di */ public function registerServices(DiInterface $di) { $oLogger = $di->getFileLogger(); // $oRouter = new Router(false); $oRouter = new CustomRouter(false); // $oOldRouter = $di->getRouter(); // Tester::ec('old router: ' . HC::className($oOldRouter)); $di->set('router', $oRouter); // Tester::ec('new router set: ' . HC::className($di->getRouter())); $oRouter->mount(new ApiRoutes($di)); $oVersionLoader = new VersionLoader(); $di->set('versionLoader', $oVersionLoader); // $oApiDispatcherEventsManager = new Manager(); //// $oLogger = $di->getFileLogger(); // $oRouter = $di->getRouter(); // // $oLogger->debug('api module ' . __FUNCTION__ . ': setting up dispatcher'); // // $oApiDispatcherEventsManager->attach('dispatch', function(Event $event, Dispatcher $dispatcher, $data) use($oLogger, $oRouter){ // $oLogger->debug('api dispatcher: ' . $event->getType() . ': ' . print_r($oRouter->getMatchedRoute(), true)); // }); // // // $oDispatcher = $di->getDispatcher(); // $oDispatcher->setDefaultNamespace('App\Modules\Api\Web'); // $oDispatcher->setControllerSuffix('Homorrag'); // $oDispatcher->setEventsManager($oApiDispatcherEventsManager); $oDispatcher = new Dispatcher(); $oApiDispatcherEventsManager = new Manager(); $oApiDispatcherEventsManager->attach('dispatch:beforeDispatchLoop', function (Event $oEvent, Dispatcher $oDispatcher, $data) { /** * @type \DiCustom $di */ $di = Di::getDefault(); $oLogger = $di->getFileLogger(); $arParams = $oDispatcher->getParams(); $oLogger->debug(__CLASS__ . ': ' . $oEvent->getType() . ': trying to dispatch:' . ' module: ' . $oDispatcher->getModuleName() . ' media: ' . $arParams['media'] . ' version: v' . $arParams['major'] . '_' . $arParams['minor'] . ' controller: ' . $oDispatcher->getControllerName() . ' action: ' . $oDispatcher->getActionName()); $di->getVersionLoader()->load(); }); $oApiDispatcherEventsManager->attach('dispatch', function (Event $oEvent, Dispatcher $oDispatcher, $data) { /** * @type \DiCustom $di */ $di = Di::getDefault(); $oLogger = $di->getFileLogger(); // $oRouter = $di->getRouter(); // // $arParams = $oRouter->getParams(); // // $oLogger->debug(__CLASS__ . ': ' . $oEvent->getType() . ': trying to dispatch: from router: ' // . ' module: ' . $oRouter->getModuleName() // . ' media: ' . $arParams['media'] // . ' version: v' . $arParams['major'] . '_' . $arParams['minor'] // . ' controller: ' . $oRouter->getControllerName() // . ' action: ' . $oRouter->getActionName() // ); $arParams = $oDispatcher->getParams(); $oLogger->debug(__CLASS__ . ': ' . $oEvent->getType() . ': trying to dispatch: from dispatcher: ' . ' module: ' . $oDispatcher->getModuleName() . ' media: ' . $arParams['media'] . ' version: v' . $arParams['major'] . '_' . $arParams['minor'] . ' controller: ' . $oDispatcher->getControllerName() . ' action: ' . $oDispatcher->getActionName()); // $oLogger->debug(__CLASS__ . ': ' . $oEvent->getType()); }); $oDispatcher->setEventsManager($oApiDispatcherEventsManager); $di->setShared('dispatcher', $oDispatcher); // $di->set('dispatcher', function() use($di){ // $dispatcher = new Dispatcher(); // $oApiDispatcherEventsManager = new Manager(); // $oLogger = $di->getFileLogger(); // $oRouter = $di->getRouter(); // $oRequest = $di->getRequest(); // // $oLogger->debug('api module ' . __FUNCTION__ . ': setting up dispatcher'); // // $oApiDispatcherEventsManager->attach('dispatch', function(Event $event, Dispatcher $dispatcher, $data) use($oLogger, $oRouter, $oRequest){ // // if($event->getType() == 'beforeDispatchLoop'){ // // $arRoutes = $oRouter->getRoutes(); // // foreach ($arRoutes as $oRoute) { // $oRoute->beforeMatch(function($uri, $route) use ($oLogger){ // $oLogger->debug('__ api module dispatcher route beforeMatch: ' . $uri . $route); // // }); // $oLogger->debug('api module dispatcher: ' . $event->getType() . ': route registered: ' . $oRoute->getCompiledPattern()); // // $regPattern = $oRoute->getCompiledPattern(); // // $strUri = $oRequest->getURI(); // // if(preg_match($regPattern, $strUri)){ // $oLogger->debug('"' . $strUri . '" matched ' . $regPattern); // }else{ // $oLogger->debug('"' . $strUri . '" mismatched ' . $regPattern); // } // // } // // } // // $oLogger->debug('api dispatcher: ' . $event->getType() . ': route matched: ' . print_r($oRouter->getMatchedRoute(), true)); // $oLogger->debug('api dispatcher: ' . $event->getType() // . ' module "' . $oRouter->getModuleName() // . '" controller: "' . $oRouter->getControllerName() // . '" action: "' . $oRouter->getActionName() . '"' // ); // }); // // $dispatcher->setEventsManager($oApiDispatcherEventsManager); // $dispatcher->setDefaultNamespace('App\Modules\Api\Web'); // return $dispatcher; // }); // // // // $oConfig = new Config(array( // 'application' => array( // 'viewsDir' => __DIR__ . '/views', // 'cacheDir' => __DIR__ . '/../../../var/cache/regular' // ), // )); // // $di->get('config')->merge($oConfig); /** * Setting up the view component */ $di->set('view', function () use($oLogger) { $oView = new View(); $oView->setRenderLevel(View::LEVEL_NO_RENDER); $oView->disable(); $oLogger->debug('view: render level set to disabled'); //Disable several levels // $view->disableLevel(array( // View::LEVEL_LAYOUT => true, // View::LEVEL_MAIN_LAYOUT => true // )); return $oView; }, true); }
/** * 根据完成的Action处理积分等操作 * 在需要处理的Action成功处添加 Config('ACTION_OK', 1); * * 在执行控制器/动作方法后触发。由于此操作不可终止 * * @param Event $event * @param Dispatcher $dispatcher * * @author Hunter.<*****@*****.**> * @return bool */ public function afterDispatch(Event $event, Dispatcher $dispatcher) { if (Config('ACTION_OK') != 1) { return true; } $module = $dispatcher->getModuleName(); $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $log = $module . '-' . $controller . '-' . $action; $fp = fopen(dirname(__FILE__) . '/__ylh_my_log_Security_afterDispatch.txt', 'a+'); fwrite($fp, microtime() . ' ' . date('Y-m-d H:i:s') . "\r\n"); fwrite($fp, print_r($log, 1) . "\r\n----------------------------\r\n\r\n"); fclose($fp); // mca:module controller action // dayMax:每日最多,为0时不限制 // credit:每次多少积分 //示例: // mca:student@index@writePage // dayMax:50 // credit:10 }
/** * This action is executed before execute any action in the application. * * @param PhalconEvent $event Event object. * @param Dispatcher $dispatcher Dispatcher object. * * @return mixed */ public function beforeDispatch(PhEvent $event, Dispatcher $dispatcher) { $me = null; $config = $this->getDI()->get('config'); $cookie = $this->getDI()->get('cookie'); $session = $this->getDI()->get('session'); // check exsited cookie if ($cookie->has('remember-me')) { $rememberMe = $cookie->get('remember-me'); $userId = $rememberMe->getValue(); $myUser = UserModel::findFirst(['id = :id: AND status = :status:', 'bind' => ['id' => $userId, 'status' => UserModel::STATUS_ENABLE]]); if ($myUser) { $me = new \stdClass(); $me->id = $myUser->id; $me->email = $myUser->email; $me->name = $myUser->name; $me->role = $myUser->role; $me->roleName = $myUser->getRoleName(); $me->avatar = $myUser->avatar; } $this->session->set('me', $me); $role = $myUser->role; } else { //Get role name from session if ($session->has('me')) { $me = $session->get('me'); $role = $me->role; } else { $role = ROLE_GUEST; } } $current_resource = $dispatcher->getModuleName() . '/' . strtolower($dispatcher->getControllerName()); $current_action = $dispatcher->getActionName(); $acl = $this->getAcl($config); $allowed = $acl->isAllowed($role, $current_resource, $current_action); // var_dump($current_resource, $current_action, $allowed);die; if ($allowed === false && $me == null) { echo '<script type="text/javascript">self.location.href = "' . $this->getDI()->get('config')->global->baseUrl . 'login?redirect=' . base64_encode($this->getCurrentUrl()) . '"; </script>'; exit; } elseif ($allowed === false && $me->id > 0) { // khong co quyen + dang nhap roi echo '<script type="text/javascript">self.location.href = "' . $this->getDI()->get('config')->global->baseUrl . 'notfound' . '"; </script>'; exit; } return !$event->isStopped(); }
/** * Get the configuration structure for the plugin. * * @param \Phalcon\Config $config * @param Dispatcher $dispatcher * * @return \Phalcon\Config * * @throws Exception */ private function getConfigStructure(Config $config, Dispatcher $dispatcher) { if (isset($config->pup)) { if (!isset($config['pup']['resources'])) { // may be it is multi module configuration $module = $dispatcher->getModuleName(); if (isset($config['pup'][$module]['resources'])) { $config = $config->pup->{$module}->resources->toArray(); } else { throw new Exception('Wrong configuration, need "resources" section or module "' . $module . '" section not filled '); } } else { $config = $config->pup->resources->toArray(); } if (!isset($config['type']) || isset($config['type']) && !in_array($config['type'], $this->resourceTypes)) { throw new Exception('Wrong configuration for key "type" or the key does not exists'); } if (!isset($config['resources']) || isset($config['resources']) && !is_array($config['resources'])) { throw new Exception('Resources key must be an array'); } return $config; } else { throw new Exception('Configuration error: I couldn\'t find the configuration key "pup" '); } }