Get router
public getRouter ( ) : Zend\Router\RouteStackInterface | ||
리턴 | Zend\Router\RouteStackInterface |
public function __invoke(MvcEvent $event) { if ($event->getRouteMatch()->getMatchedRouteName() === 'oauth/authorize' || $event->getRouteMatch()->getMatchedRouteName() === 'oauth/code') { $auth = $this->authentication; if (!$auth->hasIdentity()) { //redirect to login form before granting permissions - exception would be client_credentials grant type $url = $event->getRouter()->assemble([], array('name' => 'dotuser/login')); $host = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'on' ? 'https://' : 'http://'; $host .= $_SERVER['HTTP_HOST']; $url = $host . $url . '?redirect=' . urlencode($event->getRequest()->getUriString()); $response = $event->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); exit; } else { $identity = $auth->getIdentity(); $request = $event->getRequest(); $client_id = $request->getQuery('client_id'); //check to see if user already ganted permissions and is not revoked to skip the step and redirecting directly if ($event->getRouteMatch()->getMatchedRouteName() === 'oauth/authorize') { if ($this->userRevokeStorage->isAuthorized($client_id, $identity->getUsername())) { $newRequest = new \ZF\ContentNegotiation\Request(); $newRequest->setMethod(\Zend\Http\Request::METHOD_POST); $newRequest->getPost()->set('authorized', 'yes'); $event->setRequest($newRequest); } } } } }
/** * preDispatch Event Handler * Handle authentication process * Decide where user should be redirected to when logged in or not * * * @access public * @uses AuthenticationService * @uses Response * * @param \Zend\Mvc\MvcEvent $event * @throws \Exception */ public function preDispatch(MvcEvent $event) { // ACL dispatcher is used only in HTTP requests not console requests if (!$event->getRequest() instanceof HttpRequest) { return; } $userAuth = new AuthenticationService(); $user = array(); $signInController = 'DefaultModule\\Controller\\Sign'; if ($userAuth->hasIdentity()) { $user = $userAuth->getIdentity(); } $routeMatch = $event->getRouteMatch(); $controller = $routeMatch->getParam('controller'); $action = $routeMatch->getParam('action'); if ($userAuth->hasIdentity() && isset($user['status']) && $user['status'] == 2) { $userAuth->clearIdentity(); // redirect to sign/out $url = $event->getRouter()->assemble(array('action' => 'out'), array('name' => 'defaultSign')); } else { if ($userAuth->hasIdentity() && $controller == $signInController && $action == 'in') { // redirect to index $url = $event->getRouter()->assemble(array('action' => 'index'), array('name' => 'home')); } } if (isset($url)) { $event->setResponse(new Response()); $this->redirect()->getController()->setEvent($event); $response = $this->redirect()->toUrl($url); return $response; } }
public function onRoute(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); $routeMatchName = $e->getRouteMatch()->getMatchedRouteName(); if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) { return; } $config = $serviceManager->get('Config'); $identityGuards = $config['zource_guard']['identity']; $needsIdentity = null; foreach ($identityGuards as $guard => $needed) { if (fnmatch($guard, $routeMatchName)) { $needsIdentity = $needed; break; } } if ($needsIdentity === null) { throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName)); } if (!$needsIdentity) { return; } $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService'); if ($authenticationService->hasIdentity()) { return; } $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]); $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_302); $response->getHeaders()->addHeaderLine('Location: ' . $url); return $response; }
public function onBootstrap(MvcEvent $e) { $app = $e->getApplication(); $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $sm = $app->getServiceManager(); $list = $this->whitelist; $auth = $sm->get('AuthService'); $e->getViewModel()->setVariable('hasIdentity', $auth->hasIdentity()); if ($auth->hasIdentity()) { $e->getViewModel()->setVariable('currentUserId', $auth->getStorage()->read()->id); } else { $e->getViewModel()->setVariable('currentUserId', -1); } $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) { $match = $e->getRouteMatch(); // No route match, this is a 404 if (!$match instanceof RouteMatch) { return; } else { // Route is whitelisted $name = $match->getMatchedRouteName(); if (in_array($name, $list)) { if ($auth->hasIdentity() && $name != 'login/process') { $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'home')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; } else { return; } } else { // User is authenticated if ($auth->hasIdentity() && $name != 'auth/logout') { // $id = $this->UserAuthentication()->getIdentity()->getId(); // var_dump(($auth->getIdentity())); // exit; // var_dump($name);exit; return; } else { // Redirect to the user login page, as an example $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'login')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; } } } }, -100); }
private function dispatchEvent(MvcEvent $e) { // TARGET & SERVICEMANAGER $target = $e->getTarget(); $serviceManager = $e->getApplication()->getServiceManager(); // CONFIG $config = $e->getApplication()->getServiceManager()->get('config'); // TRANSLATOR /** @var Translator $translator */ $translator = $serviceManager->get('MvcTranslator'); // LANG CONFIG $languages = $config['languages']['available']; $fallbackLocale = $config['languages']['fallback']; // ROUTER PARAM LOCALE $routeMatch = $e->getRouteMatch(); if ($routeMatch) { $urlLocale = $routeMatch->getParam('locale'); } else { /** * @todo * evtl hier noch aus der request url versuchen die locale zu lesen */ $urlLocale = $fallbackLocale; } if (strstr($_SERVER['SERVER_NAME'], '.de')) { $urlLocale = 'de'; } else { $urlLocale = 'en'; } // ROUTER /** @var \Zend\Mvc\Router\Http\TreeRouteStack $router */ $router = $e->getRouter(); // check if language is present $usedLocale = isset($languages[$urlLocale]) ? $languages[$urlLocale] : false; $usedLocaleShort = isset($languages[$urlLocale]) ? $urlLocale : false; // language not found redirect to fallback lang if (!$usedLocale && !$usedLocaleShort) { // wrong locale request $e->getRouteMatch()->setParam('locale', $fallbackLocale); $url = $e->getRouter()->assemble($e->getRouteMatch()->getParams(), array('name' => $e->getRouteMatch()->getMatchedRouteName())); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); return $response; } // add current locale as default router param $router->setDefaultParam('locale', $usedLocaleShort); $translator->setLocale($usedLocale); $translator->setFallbackLocale($usedLocale); $translator->addTranslationFile('phpArray', 'vendor/zendframework/zendframework/resources/languages/' . $usedLocaleShort . '/Zend_Validate.php', 'default', $usedLocale); \Locale::setDefault($usedLocale); AbstractValidator::setDefaultTranslator($translator); }
/** * @param MvcEvent $e * @throws \Exception * @throws \ServiceLocatorFactory\NullServiceLocatorException */ public function preDispatch(MvcEvent $e) { $application = $e->getApplication(); $sm = $application->getServiceManager(); $router = $sm->get('router'); $request = $sm->get('request'); $matchedRoute = $router->match($request); $params = $matchedRoute->getParams(); $controller = $params['controller']; if (!isset($controller)) { return false; } $currentControllerNamespace = explode('\\', $controller); if ($currentControllerNamespace[0] == 'Admin') { $sl = ServiceLocatorFactory::getInstance(); $session = new SessionContainer(); $userDetails = $session->offsetGet('userDetails'); /* Check Admin Area login */ if (!$sl->get('AuthService')->hasIdentity() or $userDetails->sitename != $this->recoverSitename($sl)) { $url = $e->getRouter()->assemble(array('action' => 'index'), array('name' => 'login')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); exit; } // Check ACL $roles = (include __DIR__ . '/config/module.acl.roles.php'); foreach ($roles as $key => $value) { if ($key == $matchedRoute->getMatchedRouteName()) { if (isset($value['resources'])) { $allowed = 0; foreach ($value['resources'] as $resource) { if ($userDetails->acl->hasResource($resource)) { $allowed = 1; } } /* No permissions, redirect... */ if ($allowed == 0) { $url = $e->getRouter()->assemble(array('lang' => 'it'), array('name' => 'admin/not-authorized')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(401); $response->sendHeaders(); exit; } } } } } }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $serviceManager = $e->getApplication()->getServiceManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $serviceManager->get('LocaleManager')->setLocale('es_ES'); if ($serviceManager->has('Translator') && $e->getRouter() instanceof TranslatorAwareInterface) { $translator = $serviceManager->get('Translator'); if ($translator instanceof TranslatorInterface) { $e->getRouter()->setTranslator($translator); $e->getRouter()->setTranslatorTextDomain('Zend\\Mvc\\Router'); } } }
public function onBootstrap(MvcEvent $e) { $this->initSession(); $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $list = array(); $auth = $e->getApplication()->getServiceManager()->get("Zend\\Authentication\\AuthenticationService"); $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) { $match = $e->getRouteMatch(); // No route match, this is a 404 if (!$match instanceof RouteMatch) { return; } // Route is whitelisted $route = $match->getMatchedRouteName(); $params = $match->getParams(); $module = explode('/', $route); /* if($_SERVER['REMOTE_ADDR'] != '127.0.0.1' && $_SERVER['SERVER_PORT'] != '443') { $url = 'Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; header(str_replace( 'www.', '' , $url)); exit(); }*/ if (@$module[0] == 'login') { if ($auth->hasIdentity()) { $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'messages')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; } else { return; } } if ($auth->hasIdentity()) { return; } else { $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'login')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; } }, -100); }
/** * @private * @param MvcEvent $event * @return void */ public function onError(MvcEvent $event) { // Do nothing if no error or if response is not HTTP response if (!$event->getParam('exception') instanceof UnauthorizedExceptionInterface || $event->getResult() instanceof HttpResponse || !$event->getResponse() instanceof HttpResponse) { return; } $router = $event->getRouter(); if ($this->authenticationService->hasIdentity()) { if (!$this->options->getRedirectWhenConnected()) { return; } $redirectRoute = $this->options->getRedirectToRouteConnected(); } else { $redirectRoute = $this->options->getRedirectToRouteDisconnected(); } $uri = $router->assemble([], ['name' => $redirectRoute]); if ($this->options->getAppendPreviousUri()) { $redirectKey = $this->options->getPreviousUriQueryKey(); $previousUri = $event->getRequest()->getUriString(); $uri = $router->assemble([], ['name' => $redirectRoute, 'query' => [$redirectKey => $previousUri]]); } $response = $event->getResponse() ?: new HttpResponse(); $response->getHeaders()->addHeaderLine('Location', $uri); $response->setStatusCode(302); $event->setResponse($response); $event->setResult($response); }
public function __invoke(MvcEvent $event) { if ($event->getViewModel()->terminate()) { /* * No need for navigation when it is not rendered anyway. */ return; } $services = $event->getApplication()->getServiceManager(); $navigation = $services->get('Core/Navigation'); $settingsMenu = $navigation->findOneBy('route', 'lang/settings'); if ($settingsMenu->hasChildren()) { /* * We already have the subnavigation. */ return; } $moduleManager = $services->get('ModuleManager'); $configPlugin = $services->get('ControllerPluginManager')->get('config'); $modules = $moduleManager->getLoadedModules(); $modulesWithSettings = $configPlugin("settings", array_keys($modules)); $routeMatch = $event->getRouteMatch(); $router = $event->getRouter(); $activeModule = $event->getParam('__settings_active_module', false); $settingsMenu->setActive((bool) $activeModule); foreach ($modulesWithSettings as $key => $param) { $page = array('label' => isset($param['navigation_label']) ? $param['navigation_label'] : ucfirst($key), 'order' => isset($param['navigation_order']) ? $param['navigation_order'] : '10', 'class' => isset($param['navigation_class']) ? $param['navigation_class'] : null, 'resource' => 'route/lang/settings', 'route' => 'lang/settings', 'router' => $router, 'action' => 'index', 'controller' => 'index', 'params' => array('lang' => 'de', 'module' => $key), 'active' => $key == $activeModule); if ($routeMatch instanceof RouteMatch) { $page['routeMatch'] = $routeMatch; } $settingsMenu->addPage($page); } }
public function checkAuth(MvcEvent $e) { $sm = $e->getApplication()->getServiceManager(); $auth = $sm->get('AuthService'); $match = $e->getRouteMatch(); if (!$match instanceof RouteMatch) { return; } $name = $match->getMatchedRouteName(); if (in_array($name, $this->publicRoutes)) { return; } //Check identity if ($auth->hasIdentity()) { $viewModel = $e->getViewModel(); $viewModel->current_user = $auth->getIdentity(); return; } $router = $e->getRouter(); $url = $router->assemble(array(), array('name' => 'auth')); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); return $response; }
/** * preDispatch Event Handler * * @param \Zend\Mvc\MvcEvent $event * @throws \Exception */ public function preDispatch(MvcEvent $event) { //@todo - Should we really use here and Controller Plugin? $userAuth = $this->getUserAuthenticationPlugin(); $acl = $this->getAclClass(); $role = AclClass::DEFAULT_ROLE; if ($userAuth->hasIdentity()) { $user = $userAuth->getIdentity(); $role = 'member'; //@todo - Get role from user! } $routeMatch = $event->getRouteMatch(); $controller = $routeMatch->getParam('controller'); $action = $routeMatch->getParam('action'); if (!$acl->hasResource($controller)) { throw new \Exception('Resource ' . $controller . ' not defined'); } if (!$acl->isAllowed($role, $controller, $action)) { $url = $event->getRouter()->assemble(array(), array('name' => 'login')); $response = $event->getResponse(); $response->headers()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); exit; } }
public function doAuthentication(MvcEvent $event) { if (!$event->getRequest() instanceof Request) { return; } $application = $event->getApplication(); $sm = $application->getServiceManager(); $match = $event->getRouteMatch(); $controller = $match->getParam('controller'); $action = $match->getParam('action'); $plugin = $sm->get('ControllerPluginManager')->get('IsAllowed'); $hasIdentity = $plugin->getIdentity(); if (!$plugin->isAllowed($controller, $action)) { $router = $event->getRouter(); $url = $router->assemble([], ['name' => 'guest' === $hasIdentity->getRoleId() ? 'user' : 'home']); $response = $event->getResponse(); $response->setStatusCode(302); //redirect to login route... // change with header('location: '.$url); if code below not working $response->getHeaders()->addHeaderLine('Location', $url); $event->stopPropagation(); return $response; } return; }
/** * @param MvcEvent $e */ protected function handleError(MvcEvent $e) { $router = $e->getRouter(); if ($this->authenticationService->hasIdentity()) { if (!$this->options->getRedirectWhenConnected()) { return; } $redirectRoute = $this->options->getRedirectToRouteConnected(); } else { $redirectRoute = $this->options->getRedirectToRouteDisconnected(); } $params = array(); $options = array('name' => $redirectRoute); if ($this->options->getAppendPreviousUri()) { $redirectKey = $this->options->getPreviousUriRouteKey(); $previousUri = $e->getRequest()->getUriString(); $params = array($redirectKey => $previousUri); } $uri = $router->assemble($params, $options); $response = $e->getResponse() ?: new HttpResponse(); $response->getHeaders()->addHeaderLine('Location', $uri); $response->setStatusCode(302); $e->setResponse($response); $e->setResult($response); }
public function restrictAccess(MvcEvent $e, array $whiteListed = array(), $loginRouteName = 'admin/login') { // $loginRouteName is whitelisted from the redirection // The redirection is to the $loginRouteName // additional routes can be whitelisted if (!$e->getApplication()->getServiceManager()->get('Zend\\Authentication\\AuthenticationService')->hasIdentity()) { $whiteListed[] = $loginRouteName; $match = $e->getRouteMatch(); // No route match, this is a 404 if (!$match instanceof RouteMatch) { return; } // Login route is whitelisted if (in_array($match->getMatchedRouteName(), $whiteListed)) { return; } // login url from login route $url = $e->getRouter()->assemble(array(), array('name' => $loginRouteName)); // redirect response $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); exit; } }
/** * Listens to the route event. * * Detects the language to use and sets translator locale. * The language is detected either via query parameter "lang" or * browser setting (ACCEPT-LANGUAGE header) * * @param MvcEvent $e */ public function onRoute(MvcEvent $e) { /* @var $request \Zend\Http\PhpEnvironment\Request */ $request = $e->getRequest(); /* Detect language */ $lang = $request->getQuery('lang'); if (!$lang) { $headers = $request->getHeaders(); if ($headers->has('Accept-Language')) { /* @var $acceptLangs \Zend\Http\Header\AcceptLanguage */ $acceptLangs = $headers->get('Accept-Language'); $locales = $acceptLangs->getPrioritized(); $locale = $locales[0]; $lang = $locale->type; } else { $lang = 'en'; } } /* Set locale */ $translator = $e->getApplication()->getServiceManager()->get('mvctranslator'); $locale = $lang . '_' . strtoupper($lang); setlocale(LC_ALL, array($locale . ".utf8", $locale . ".iso88591", $locale, substr($locale, 0, 2), 'de_DE.utf8', 'de_DE', 'de')); \Locale::setDefault($locale); $translator->setLocale($locale); $routeMatch = $e->getRouteMatch(); if ($routeMatch && $routeMatch->getParam('lang') === null) { $routeMatch->setParam('lang', $lang); } /* @var $router \Zend\Mvc\Router\SimpleRouteStack */ $router = $e->getRouter(); $router->setDefaultParam('lang', $lang); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) { $controller = $e->getTarget(); $routeMatch = $e->getRouteMatch(); $parkingLotId = $routeMatch->getParam('parking_lot_id', 0); // get the parking lot id if (method_exists($controller, 'setParkingLotId')) { $serviceManager = $e->getApplication()->getServiceManager(); $dbAdapter = $serviceManager->get('Zend\\Db\\Adapter\\Adapter'); $parkingLotExistsValidator = new RecordExists(['adapter' => $dbAdapter, 'table' => DbTables::TBL_PARKING_LOTS, 'field' => 'id']); if (!$parkingLotExistsValidator->isValid($parkingLotId) && $parkingLotId != 0) { $url = $e->getRouter()->assemble(['controller' => 'parking', 'action' => 'index'], ['name' => 'parking']); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); return $response; } $controller->setParkingLotId($parkingLotId); } }, 100); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach(MvcEvent::EVENT_ROUTE, [$this, 'onViewHelper']); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($e) { $controller = $e->getTarget(); $routeMatch = $e->getRouteMatch(); $apartmentId = $routeMatch->getParam('apartment_id', 0); // get the apartment ID if (method_exists($controller, 'setApartmentID')) { $serviceManager = $e->getApplication()->getServiceManager(); $dbAdapter = $serviceManager->get('Zend\\Db\\Adapter\\Adapter'); $apartmentExistValidator = new RecordExists(['adapter' => $dbAdapter, 'table' => DbTables::TBL_APARTMENTS, 'field' => 'id']); if (!$apartmentExistValidator->isValid($apartmentId) && $apartmentId != 0) { $url = $e->getRouter()->assemble(array('controller' => 'apartment', 'action' => 'search'), ['name' => 'apartments']); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); return $response; } $controller->setApartmentID($apartmentId); } }, 100); }
public function checkAuthentication(MvcEvent $event) { if ($event->getRequest() instanceof ConsoleResquest) { return; } $routename = $event->getRouteMatch()->getMatchedRouteName(); // TODO mettre en conf if ($routename == 'zfcuser/login' || $routename == 'zfcuser/logout' || $routename == 'execution') { return; } $zfcUser = $this->getServiceLocator()->get('zfcuser_auth_service'); $config = $this->getServiceLocator()->get('Config'); $authorized = false; if ($zfcUser->hasIdentity()) { $authorized = $this->getFileAuthService()->checkAutorisation($zfcUser->getIdentity()->getUserName(), $routename); } if (!$zfcUser->hasIdentity() || true !== $authorized) { $url = $event->getRouter()->assemble(array(), array('name' => 'zfcuser/login')); $response = $event->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); $stopCallBack = function ($event) use($response) { $event->stopPropagation(); return $response; }; $event->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE, $stopCallBack, -10000); return $response; } }
public function onDispatch(MvcEvent $mvcEvent) { $renderer = $this->serviceLocator->get('Zend\\View\\Renderer\\PhpRenderer'); $jsFile = 'pwstrength.js'; $baseUrl = $mvcEvent->getRouter()->getBaseUrl(); $renderer->headScript()->appendFile($baseUrl . '/js/' . $jsFile); return parent::onDispatch($mvcEvent); }
public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $config = $e->getApplication()->getServiceManager()->get('Config'); $router = $e->getRouter(); $router->addRoutes(array('ldap-login-route' => array('type' => 'Zend\\Mvc\\Router\\Http\\Literal', 'options' => array('route' => $config['ldap_config']['login_route'], 'defaults' => array('__NAMESPACE__' => 'Zf2LdapAuth\\Controller', 'controller' => 'Login', 'action' => 'login'))), 'ldap-logout-route' => array('type' => 'Zend\\Mvc\\Router\\Http\\Literal', 'options' => array('route' => $config['ldap_config']['logout_route'], 'defaults' => array('__NAMESPACE__' => 'Zf2LdapAuth\\Controller', 'controller' => 'Logout', 'action' => 'index'))))); }
public function setUp() { Console::overrideIsConsole(false); parent::setUp(); $this->request = new Request(); $this->request->setHeaders(new Headers()); $this->routeMatch = new RouteMatch(array('controller' => $this->controllerName)); $this->event = $this->getApplication()->getMvcEvent(); $this->event->setRequest($this->request); $this->event->setRouteMatch($this->routeMatch); $this->event->getRouter()->setRequestUri(new HttpUri('http://localhost')); if (null === $this->controller) { if (null === $this->controllerName) { throw new PHPUnit_Framework_Exception('No controller name was specified in the test'); } $this->controller = $this->getServiceManager()->get('ControllerLoader')->get($this->controllerName); } $this->controller->setEvent($this->event); }
function boforeDispatch(MvcEvent $event) { date_default_timezone_set('Asia/Ho_Chi_Minh'); $sm = $event->getApplication()->getServiceManager(); $auth = $sm->get('AuthService'); $read = $sm->get("AuthService")->getStorage()->read(); // nếu chưa có white_list if (!isset($read['white_list']) and !$auth->hasIdentity() || !isset($read['user_id'])) { // lấy white_list chưa đăng nhập $jos_admin_resource_table = $sm->get('Permission\\Model\\JosAdminResourceTable'); $white_list = $jos_admin_resource_table->getResourceByWhiteList(1); $sm->get("AuthService")->getStorage()->write(array('white_list' => $white_list)); // nếu chưa đăng nhập thì chỉ được vào trang đăng nhập $response = $event->getResponse(); $response->getHeaders()->addHeaderLine('Location', $event->getRouter()->assemble(array('action' => 'login'), array('name' => 'permission/permission'))); $response->setStatusCode(302); return $response; } $read = $sm->get("AuthService")->getStorage()->read(); $white_lists = $read['white_list']; // url cần chuyển tới $params = $event->getRouteMatch()->getParams(); $controller = $params['controller']; $action = $this->fixRoute($params['action']); // duyệt qua white_list nếu không nằm trong white list thì không có quyền $is_white_list = 0; foreach ($white_lists as $key => $white_list) { if ($white_list['controller'] == $controller and $white_list['action'] == $action) { $is_white_list = 1; break; } } if ($is_white_list == 0) { if (!$auth->hasIdentity() || !isset($read['user_id'])) { // nếu chưa đăng nhập thì chỉ được vào trang đăng nhập $response = $event->getResponse(); $response->getHeaders()->addHeaderLine('Location', $event->getRouter()->assemble(array('action' => 'login'), array('name' => 'permission/permission'))); $response->setStatusCode(302); return $response; } die('Xin loi, Duong dan khong hop le. Vui long kiem tra lai!'); } }
public function onCheckAuthentication(MvcEvent $e) { $authenticationService = $e->getApplication()->getServiceManager()->get('application.authentication.service'); if (!$authenticationService->hasIdentity() && $e->getRouteMatch()->getMatchedRouteName() !== 'login') { $response = $e->getResponse(); $response->setStatusCode(Response::STATUS_CODE_302); $headers = $response->getHeaders(); $headers->addHeaderLine('Location: ' . $e->getRouter()->assemble([], ['name' => 'login'])); return $response; } }
/** * Sets up services on the bootstrap event. * * @internal * Creates the translation service and a ModuleRouteListener * * @param MvcEvent $e */ public function onBootstrap(MvcEvent $e) { // Register the TimezoneAwareDate type with DoctrineMongoODM // Use it in Annotions ( @Field(type="tz_date") ) if (!DoctrineType::hasType('tz_date')) { DoctrineType::addType('tz_date', '\\Core\\Repository\\DoctrineMongoODM\\Types\\TimezoneAwareDate'); } $sm = $e->getApplication()->getServiceManager(); $translator = $sm->get('translator'); // initialise translator! \Zend\Validator\AbstractValidator::setDefaultTranslator($translator); $eventManager = $e->getApplication()->getEventManager(); $sharedManager = $eventManager->getSharedManager(); # $LogListener = new LogListener(); # $LogListener->attach($eventManager); if (!\Zend\Console\Console::isConsole()) { $redirectCallback = function () use($e) { $routeMatch = $e->getRouteMatch(); $lang = $routeMatch ? $routeMatch->getParam('lang', 'en') : 'en'; $uri = $e->getRouter()->getBaseUrl() . '/' . $lang . '/error'; header('Location: ' . $uri); }; $errorHandlerListener = new ErrorHandlerListener($sm->get('ErrorLogger'), $redirectCallback); $errorHandlerListener->attach($eventManager); $languageRouteListener = new LanguageRouteListener(); $languageRouteListener->attach($eventManager); $ajaxRenderListener = new AjaxRenderListener(); $ajaxRenderListener->attach($eventManager); $enforceJsonResponseListener = new EnforceJsonResponseListener(); $enforceJsonResponseListener->attach($eventManager); $stringListener = new StringListener(); $stringListener->attach($eventManager); // $notificationlistener = $sm->get('Core/Listener/Notification'); $notificationlistener->attachShared($sharedManager); $notificationAjaxHandler = new NotificationAjaxHandler(); $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20); $notificationlistener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20); } $persistenceListener = new PersistenceListener(); $persistenceListener->attach($eventManager); $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($event) { $application = $event->getApplication(); if ($application::ERROR_EXCEPTION == $event->getError()) { $ex = $event->getParam('exception'); if (404 == $ex->getCode()) { $event->setError($application::ERROR_CONTROLLER_NOT_FOUND); } } }, 500); $eventManager->attach(MvcEvent::EVENT_DISPATCH, function ($event) use($eventManager) { $eventManager->trigger('postDispatch', $event); }, -150); }
public function handleControllerNotFoundAndControllerInvalidAndRouteNotFound(MvcEvent $e) { $error = $e->getError(); $typeErreur = null; if ($error == Application::ERROR_CONTROLLER_NOT_FOUND) { //there is no controller named $e->getRouteMatch()->getParam('controller') $typeErreur = 2; } if ($error == Application::ERROR_CONTROLLER_INVALID) { //the controller doesn't extends AbstractActionController $typeErreur = 3; } if ($error == Application::ERROR_ROUTER_NO_MATCH) { // the url doesn't match route, for example, there is no /foo literal of route $typeErreur = 4; } if ($typeErreur != null) { $url = $e->getRouter()->assemble(array('erreur' => 'erreur'), array('name' => 'home', 'query' => array('erreur' => $typeErreur))); $response = $e->getResponse(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $response->sendHeaders(); return $response; } }
public function onDispatchError(MvcEvent $e) { // Do nothing if the result is a response object $result = $e->getResult(); $type = $e->getError(); if ($result instanceof Response || strpos($type, 'unauthorized') === false) { return; } $router = $e->getRouter(); $match = $e->getRouteMatch(); // get url to the zfcuser/login route $options['name'] = 'zfcuser/login'; $url = $router->assemble(array(), $options); // Work out where were we trying to get to $options['name'] = $match->getMatchedRouteName(); $redirect = $router->assemble($match->getParams(), $options); // set up response to redirect to login page $response = $e->getResponse(); if (!$response) { $response = new HttpResponse(); $e->setResponse($response); } $response->getHeaders()->addHeaderLine('Location', $url . '?redirect=' . $redirect); $response->setStatusCode(302); }
/** * Handles redirects in case of dispatch errors caused by unauthorized access * * @param \Zend\Mvc\MvcEvent $event */ public function onDispatchError(MvcEvent $event) { // Do nothing if the result is a response object $result = $event->getResult(); $routeMatch = $event->getRouteMatch(); $response = $event->getResponse(); $router = $event->getRouter(); $error = $event->getError(); $url = $this->redirectUri; if ($result instanceof Response || !$routeMatch || $response && !$response instanceof Response || !(Route::ERROR === $error || Controller::ERROR === $error || Application::ERROR_EXCEPTION === $error && $event->getParam('exception') instanceof UnAuthorizedException)) { return; } // if application needs install if (AppGuard::ERROR === $error && $event->getParam('exception') instanceof NeedsInstallException) { die('died here'); $this->redirectRoute = 'zfmuscle/install'; } if (null === $url) { $url = $router->assemble(array(), array('name' => $this->redirectRoute)); } $response = $response ?: new Response(); $response->getHeaders()->addHeaderLine('Location', $url); $response->setStatusCode(302); $event->setResponse($response); }
/** * Create an exception view model, and set the HTTP status code * * @todo dispatch.error does not halt dispatch unless a response is * returned. As such, we likely need to trigger rendering as a low * priority dispatch.error event (or goto a render event) to ensure * rendering occurs, and that munging of view models occurs when * expected. * @param MvcEvent $e * @return void */ public function prepareExceptionViewModel(MvcEvent $e) { // Do nothing if no error in the event $error = $e->getError(); if (empty($error)) { return; } // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof Response) { return; } // Do nothing if there is no exception or the exception is not // an UnauthorizedAccessException $exception = $e->getParam('exception'); if (!$exception instanceof UnauthorizedAccessException) { return; } $response = $e->getResponse(); if (!$response) { $response = new Response(); $e->setResponse($response); } /* * Return an image, if an image was requested. */ if ($exception instanceof UnauthorizedImageAccessException) { $image = __DIR__ . '/../../../../../public/images/unauthorized-access.png'; $response->setStatusCode(403)->setContent(file_get_contents($image))->getHeaders()->addHeaderLine('Content-Type', 'image/png'); $e->stopPropagation(); $response->sendHeaders(); //echo file_get_contents($image); //$response->stopped = true; return $response; } $auth = $e->getApplication()->getServiceManager()->get('AuthenticationService'); if (!$auth->hasIdentity()) { $response->setStatusCode(Response::STATUS_CODE_403); $routeMatch = $e->getRouteMatch(); $routeMatch->setParam('controller', 'Auth\\Controller\\Index'); $routeMatch->setParam('action', 'index'); $query = $e->getRequest()->getQuery(); $ref = $e->getRequest()->getRequestUri(); $ref = preg_replace('~^' . preg_quote($e->getRouter()->getBaseUrl()) . '~', '', $ref); $query->set('ref', $ref); $query->set('req', 1); $result = $e->getApplication()->getEventManager()->trigger('dispatch', $e); $e->stopPropagation(); return $result; } $message = $exception->getMessage(); $model = new ViewModel(array('message' => empty($message) ? 'You are not permitted to access this resource.' : $message, 'exception' => $e->getParam('exception'), 'display_exceptions' => $this->displayExceptions())); $model->setTemplate($this->getExceptionTemplate()); $e->setResult($model); // $statusCode = $response->getStatusCode(); // if ($statusCode === 200) { $response->setStatusCode(403); // } }
public function onDispatchError(MvcEvent $e) { $result = $e->getResult(); $response = $e->getResponse(); if ($result instanceof Response || $response && !$response instanceof HttpResponse) { return; } $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity')); switch ($e->getError()) { case Controller::ERROR: $viewVariables['controller'] = $e->getParam('controller'); $viewVariables['action'] = $e->getParam('action'); $router = $e->getRouter(); if ($e->getParam('exception') instanceof UnAuthorizedException && !$e->getApplication()->getServiceManager()->get('Zend\\Authentication\\AuthenticationService')->hasIdentity()) { $session = new Container('location'); $session->location = $e->getRequest()->getUri(); // get url to the login route $options['name'] = 'login'; $url = $router->assemble(array(), $options); if (!$response) { $response = new HttpResponse(); $e->setResponse($response); } if ($e->getRequest()->isXmlHttpRequest()) { $response->setStatusCode(204); $response->getHeaders()->addHeaderLine('Fury-Redirect', $url); } else { $response->setStatusCode(302); $response->getHeaders()->addHeaderLine('Location', $url); } return; } break; case Route::ERROR: $viewVariables['route'] = $e->getParam('route'); break; case Application::ERROR_EXCEPTION: if (!$e->getParam('exception') instanceof UnAuthorizedException) { return; } $viewVariables['reason'] = $e->getParam('exception')->getMessage(); $viewVariables['error'] = 'error-unauthorized'; break; default: /* * do nothing if there is no error in the event or the error * does not match one of our predefined errors (we don't want * our 403 template to handle other types of errors) */ return; } $model = new ViewModel($viewVariables); $response = $response ?: new HttpResponse(); $model->setTemplate($this->getTemplate()); $e->getViewModel()->addChild($model); $response->setStatusCode(403); $e->setResponse($response); }