public function processUnAuth(MvcEvent $e) { //$d = new \Zend\Debug\Debug(); $d->dump($e->getError()); $error = $e->getError(); if ($e->getError() === 'error-route-unauthorized') { $sm = $e->getApplication()->getServiceManager(); $conf = $sm->get('IdAuth\\Config'); if ($conf['settings']['useDifferentLayoutForUnAuth']) { $user = new Forms\Login(); $builder = new \Zend\Form\Annotation\AnnotationBuilder(); $loginForm = $builder->createForm($user); $view = $e->getViewModel(); $view->loginForm = $loginForm; $view->setTemplate('idauth/locked'); $view->error = $error; $auth = $sm->get('IdAuthService'); $hasIdentity = $auth->hasIdentity(); if ($hasIdentity) { $view->gravatarEmail = $auth->getIdentity()->getEmail(); } else { $view->gravatarEmail = null; } $view->hasIdentity = $auth->hasIdentity(); $view->identity = $auth->getIdentity(); $view->route = $e->getRouteMatch()->getMatchedRouteName(); } } }
/** * Verify is error * * @throws \LogicException */ private function verifyIsError() { $error = $this->mvcEvent->getError(); if (!$error) { throw new \LogicException("This listener is only meant to be called on errors"); } }
/** * @param MvcEvent $event */ public function dispatchError(MvcEvent $event) { $exception = $event->getParam('exception'); while ($exception) { $this->logger->critical('EVENT_DISPATCH_ERROR: ' . $exception->getMessage(), $exception->getTrace()); $exception = $exception->getPrevious(); } if ($event->isError() == true && $event->getError() == Application::ERROR_EXCEPTION) { $this->logger->critical('EVENT_DISPATCH_ERROR: ' . $event->getError()); } }
public function onBootstrap(MvcEvent $event) { $eventManager = $event->getApplication()->getEventManager(); $oauth2Closure = $event->getApplication()->getServiceManager()->get(\ZF\OAuth2\Service\OAuth2Server::class); $logger = $event->getApplication()->getServiceManager()->get('logger'); $eventManager->attach(MvcAuthEvent::EVENT_AUTHENTICATION_POST, function (MvcAuthEvent $event) use($oauth2Closure) { // Manipulating Identity Data $identity = $event->getIdentity(); if (!!$identity) { if ($identity instanceof AuthenticatedIdentity) { $userData = $oauth2Closure()->getStorage('user_credentials')->getUser($identity->getName()); if (is_array($identity->getAuthenticationIdentity())) { $userData = array_merge($userData, $identity->getAuthenticationIdentity()); } $identity = new AuthenticatedIdentity($userData); $event->setIdentity($identity); } //MvcEvent did not understand when manipulated MvcAuthEvent identity $event->getMvcEvent()->setParam('ZF\\MvcAuth\\Identity', $identity); } return $event; }, 900); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $event->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR, function (MvcEvent $event) use($logger) { $problem = null; if ($event->isError()) { $exception = $event->getParam("exception"); // There are some other errors like that : // "error-controller-cannot-dispatch", // "error-controller-invalid", // "error-controller-not-found", // "error-router-no-match", if ($event->getError() === 'error-controller-not-found') { $problem = new ApiProblem(404, "Endpoint controller not found!"); } elseif ($event->getError() === 'error-router-no-match') { $problem = new ApiProblem(404, "Not found!"); } elseif ($exception instanceof \Exception) { $className = explode('\\', get_class($exception)); $problem = new ApiProblem($exception->getCode(), end($className) . ' error.'); $logger->err($exception->getMessage(), array('controller' => $event->getControllerClass())); } } else { $problem = new ApiProblem(500, "Unknown Error!"); } $response = new ApiProblemResponse($problem); $event->stopPropagation(); return $response; }, 9000); }
/** * @param \Zend\Mvc\MvcEvent $object * @param array $options * * @return array */ public function format($object, array $options) { $data['route']['name'] = $object->getRouteMatch()->getMatchedRouteName(); $data['route']['params'] = $object->getRouteMatch()->getParams(); $parts = explode('/', $data['route']['name']); $route = $object->getRouter(); $config = $object->getApplication()->getServiceManager()->get('config'); $config = isset($config['router']['routes']) ? $config['router']['routes'] : []; while ($part = array_shift($parts)) { $route->hasRoute($part) and $route = $route->getRoute($part); isset($config[$part]) and $config = $config[$part]; } $data['route']['class'] = get_class($route); $data['route']['assembled'] = $route->getAssembledParams(); $data['event']['error'] = $object->getError(); $data['event']['name'] = $object->getName(); $controllers = []; $definitions = []; $title = '404 Error'; $subtitle = 'Unknown Error'; $context = null; $manager = $object->getApplication()->getServiceManager()->get('ControllerLoader'); switch ($object->getError()) { case Application::ERROR_CONTROLLER_NOT_FOUND: $definitions = $config; $title = $object->getControllerClass(); $subtitle = 'The requested controller cannot be found'; $controllers = $manager->getCanonicalNames(); array_pop($controllers); // because the Sm add the wrong into the list break; case Application::ERROR_CONTROLLER_INVALID: $title = $object->getControllerClass(); $subtitle = $object->getParam('exception')->getMessage(); break; case Application::ERROR_CONTROLLER_CANNOT_DISPATCH: $context = $this->getControllerContext($manager, $data['route']['params']); $subtitle = 'The controller cannot dispatch the request'; $title = $data['route']['params']['controller']; break; } $data['title'] = $title; $data['subtitle'] = $subtitle; $data['route']['definition'] = $definitions; $data['controller']['names'] = $controllers; $data['controller']['context'] = $context; return $data; }
/** * Callback used when a dispatch error occurs. Modifies the * response object with an according error if the application * event contains an exception related with authorization. * * @param MvcEvent $event * * @return void */ public function onDispatchError(MvcEvent $event) { // Do nothing if the result is a response object $result = $event->getResult(); $response = $event->getResponse(); if ($result instanceof Response || $response && !$response instanceof HttpResponse) { return; } // Common view variables $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity')); switch ($event->getError()) { case Application::ERROR_EXCEPTION: if (!$event->getParam('exception') instanceof UnAuthorizedException) { return; } $viewVariables['reason'] = $event->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()); $event->getViewModel()->addChild($model); $response->setStatusCode(403); $event->setResponse($response); }
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; } }
/** * Keep the same layout if user access forbidden page * * @param MvcEvent $e */ public function keepLayout(MvcEvent $e) { $error = $e->getError(); if (empty($error) || in_array($error, [AclListener::ERROR_FORBIDDEN, AbstractControllerGuard::ERROR_FORBIDDEN])) { $this->updateLayout($e); } }
public function onDispatchError(MvcEvent $event) { switch ($event->getError()) { case AccessService::ACCESS_DENIED: $statusCode = 403; break; case AccessService::ACCESS_UNAUTHORIZED: $statusCode = 401; break; default: // do nothing if this is a different kind of error we should not trap return; } if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $viewModel = new JsonModel(); } else { $viewModel = new ViewModel(); $viewModel->setTemplate('user/' . $statusCode); } $viewModel->setVariables($event->getParams()); $response = $event->getResponse() ?: new Response(); $response->setStatusCode($statusCode); $event->setViewModel($viewModel); $event->setResponse($response); }
/** * Create a custom event in Zend Server * * @param MvcEvent $e * @return void */ public function createCustomEvent(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; } switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: if (!empty($e)) { $exception = $e->getParam('exception'); /* @var $exception \Exception */ $message = 'An error occurred during execution: ' . $exception->getMessage(); if ($this->isCustomEventByRuleIsEnabled()) { zend_monitor_custom_event_ex('Zend Framework Exception', $message, 'Zend Framework Exception Rule'); } elseif ($this->isCustomEventIsEnabled) { zend_monitor_custom_event('Zend Framework Exception', $message); } } } }
/** * @param MvcEvent $event */ public function onDispatchError(MvcEvent $event) { if (Application::ERROR_ROUTER_NO_MATCH != $event->getError()) { // ignore other than 'no route' errors return; } // get URI stripped of a base URL $request = $event->getRequest(); $uri = str_replace($request->getBaseUrl(), '', $request->getRequestUri()); // try get image ID from URI $id = $this->manager->matchUri($uri); if (!$id) { // abort if URI does not match return; } // try get image from repository $image = $this->repository->find($id); if (!$image) { // abort if image does not exist return; } // store image $this->manager->store($image); // return image in response as a stream $headers = new Headers(); $headers->addHeaders(['Content-Type' => $image->getType(), 'Content-Length' => $image->getLength()]); $response = new Stream(); $response->setStatusCode(Response::STATUS_CODE_200); $response->setStream($image->getResource()); $response->setStreamName($image->getName()); $response->setHeaders($headers); $event->setResponse($response); }
public function __invoke(MvcEvent $event) { $model = $event->getResult(); if (!$model instanceof ViewModel) { return; } if (strpos($model->getTemplate(), 'error') === false) { return; } $result = $event->getResult(); $error = $event->getError(); $layout = new ViewModel(); $layout->setTemplate('layout/layout'); $content = new ViewModel(); if ($error == 'error-exception') { $content->setVariable('reason', 'The site seems to be experiencing problems, please try again later'); $content->setTemplate('error/knc-exception'); } else { $content->setVariable('reason', 'The site cannot find the url in the address bar'); $content->setTemplate('error/knc-error'); } $layout->addChild($content); $layout->setTerminal(true); $event->setViewModel($layout); $event->setResult($layout); return false; }
/** * 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); }
public function prepareExceptionViewModel(MvcEvent $event) { // Do nothing if no error in the event $error = $event->getError(); if (empty($error)) { return; } // Do nothing if the result is a response object $result = $event->getResult(); if ($result instanceof Response) { return; } switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: $exception = $event->getParam('exception'); if ($exception) { $response = $event->getResponse(); if (!$response || $response->getStatusCode() === 200) { header('HTTP/1.0 500 Internal Server Error', true, 500); } ob_clean(); $this->run->handleException($event->getParam('exception')); } break; } }
/** * Whoops handle exceptions * @param MvcEvent $e */ public function prepareException(MvcEvent $e) { if ($e->getRequest() instanceof Request) { $error = $e->getError(); if (!empty($error) && !$e->getResult() instanceof Response) { switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: /** @var Exception $exception */ $exception = $e->getParam('exception'); // Filter exceptions that we must except foreach ($this->whoopsConfig['blacklist'] as $except) { if ($exception instanceof $except) { return; } } if ($this->whoopsConfig['handler']['options_type'] === 'prettyPage') { $response = $e->getResponse(); if (!$response || $response->getStatusCode() === 200) { header('HTTP/1.0 500 Internal Server Error', true, 500); } ob_clean(); } $this->run->handleException($e->getParam('exception')); break; } } } }
/** * Whoops handle exceptions * @param MvcEvent $e */ public function prepareException(MvcEvent $e) { $error = $e->getError(); if (!empty($error) && !$e->getResult() instanceof Response) { switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: if (in_array(get_class($e->getParam('exception')), $this->noCatchExceptions)) { // No catch this exception return; } $response = $e->getResponse(); if (!$response || $response->getStatusCode() === 200) { header('HTTP/1.0 500 Internal Server Error', true, 500); } ob_clean(); $this->run->handleException($e->getParam('exception')); break; } } }
public function handleError(MvcEvent $event) { // Do nothing if no error in the event $error = $event->getError(); if (empty($error)) { return; } switch ($error) { case Application::ERROR_CONTROLLER_NOT_FOUND: case Application::ERROR_CONTROLLER_INVALID: case Application::ERROR_ROUTER_NO_MATCH: // Specifically not handling these return; case Application::ERROR_EXCEPTION: default: $exception = $event->getParam('exception'); $logMessages = array(); do { $priority = Logger::ERR; $extra = array('file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTrace()); if (isset($exception->xdebug_message)) { $extra['xdebug'] = $exception->xdebug_message; } $logMessages[] = array('priority' => $priority, 'message' => $exception->getMessage(), 'extra' => $extra); $exception = $exception->getPrevious(); } while ($exception); foreach (array_reverse($logMessages) as $logMessage) { $this->log->log($logMessage['priority'], $logMessage['message'], $logMessage['extra']); } break; } }
public function prepareViewModel(MvcEvent $e) { // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof Response) { return; } // Common view variables $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity')); $error = $e->getError(); switch ($error) { case 'error-unauthorized-controller': $viewVariables['controller'] = $e->getParam('controller'); $viewVariables['action'] = $e->getParam('action'); break; case 'error-unauthorized-route': $viewVariables['route'] = $e->getParam('route'); break; default: // Do nothing if no error in the event return; } $model = new ViewModel($viewVariables); $model->setTemplate($this->getTemplate()); $e->getViewModel()->addChild($model); $response = $e->getResponse(); if (!$response) { $response = new HttpResponse(); $e->setResponse($response); } $response->setStatusCode(403); }
/** * @see \Zend\Mvc\View\Http\ExceptionStrategy::prepareExceptionViewModel() */ public function prepareExceptionViewModel(MvcEvent $event) { // do nothing if no error in the event $error = $event->getError(); if (empty($error)) { return; } // do nothing if the result is a response object $result = $event->getResult(); if ($result instanceof Response) { return; } // do nothing if there is no exception or the exception is not an UserDeactivatedException $exception = $event->getParam('exception'); if (!$exception instanceof UserDeactivatedException) { return; } $auth = $event->getApplication()->getServiceManager()->get('AuthenticationService'); // do nothing if no user is logged in or is active one if (!$auth->hasIdentity() || $auth->getUser()->isActive()) { return; } $response = $event->getResponse(); if (!$response) { $response = new Response(); $event->setResponse($response); } $response->setStatusCode(Response::STATUS_CODE_403); $model = new ViewModel(['message' => 'This user account has been disabled. Please contact the system adminstrator.', 'exception' => $exception, 'display_exceptions' => $this->displayExceptions()]); $model->setTemplate($this->getExceptionTemplate()); $event->setResult($model); }
/** * Listen for specific thrown exceptions and display the proper error page * and code for each. * * @param MvcEvent $e */ public function handleException(MvcEvent $e) { $result = $e->getResult(); // Don't interfere with a complete response. if ($result instanceof ResponseInterface) { return; } // Only handle exceptions. if ($e->getError() !== ZendApplication::ERROR_EXCEPTION) { return; } $exception = $e->getParam('exception'); $this->getServiceLocator()->get('Omeka\\Logger')->err((string) $exception); if ($exception instanceof AclException\PermissionDeniedException) { $template = 'error/403'; $status = 403; } else { if ($exception instanceof ApiException\NotFoundException || $exception instanceof MvcException\NotFoundException) { $template = 'error/404'; $status = 404; } else { return; } } $model = new ViewModel(['exception' => $exception]); $model->setTemplate($template); $response = $e->getResponse(); if (!$response) { $response = new Response(); } $response->setStatusCode($status); $e->setResponse($response); $e->getViewModel()->addChild($model); }
/** * @param MvcEvent $e * @return void|ViewModel */ public function handleDispatchErrors(MvcEvent $e) { $exception = $e->getParam('exception'); $routeMatch = $e->getRouteMatch(); if (!$routeMatch || $exception instanceof UnauthorizedException) { // We don't handle permissions errors or unmatched routes return; } // We will do the final handling here $e->stopPropagation(); if (Console::isConsole()) { return; } $error = $e->getError(); $model = new ViewModel( [ 'message' => 'An error occurred. Good luck!<br/><br/><pre>' . $exception->getMessage() . '</pre>', 'reason' => $error, 'exception' => $exception, ] ); $model->setTemplate('error/404'); $e->getViewModel()->addChild($model); $response = $e->getResponse(); $response->setStatusCode(404); return $model; }
/** * Create an unauthorized view model, and set the HTTP status code * * @param MvcEvent $e * @return void */ public function prepareUnauthorizedViewModel(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; } switch ($error) { case Security::ERROR_CONTROLLER_UNAUTHORIZED: $model = new ViewModel(array('error' => $e->getParam('error'), 'controller' => $e->getParam('controller'), 'action' => $e->getParam('action'), 'identity' => $e->getParam('identity'))); break; case Security::ERROR_ROUTE_UNAUTHORIZED: $model = new ViewModel(array('error' => $e->getParam('error'), 'route' => $e->getParam('route'), 'identity' => $e->getParam('identity'))); break; default: return; break; } $model->setTemplate($this->getUnauthorizedTemplate()); $e->setResult($model); $response = $e->getResponse(); if (!$response) { $response = new HttpResponse(); $e->setResponse($response); } $response->setStatusCode(403); }
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); }
public function renderAssets(MvcEvent $e) { $sm = $e->getApplication()->getServiceManager(); /** @var Configuration $config */ $config = $sm->get('AsseticConfiguration'); if ($e->getName() === MvcEvent::EVENT_DISPATCH_ERROR) { $error = $e->getError(); if ($error && !in_array($error, $config->getAcceptableErrors())) { // break if not an acceptable error return; } } $response = $e->getResponse(); if (!$response) { $response = new Response(); $e->setResponse($response); } /** @var $asseticService \AsseticBundle\Service */ $asseticService = $sm->get('AsseticService'); // setup service if a matched route exist $router = $e->getRouteMatch(); if ($router) { $asseticService->setRouteName($router->getMatchedRouteName()); $asseticService->setControllerName($router->getParam('controller')); $asseticService->setActionName($router->getParam('action')); } // Create all objects $asseticService->build(); // Init assets for modules $asseticService->setupRenderer($sm->get('ViewRenderer')); }
public function onDispatchError(MvcEvent $event) { $result = $event->getResult(); $response = $event->getResponse(); if ($result instanceof Response || $response && !$response instanceof HttpResponse) { return; } $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity')); switch ($event->getError()) { case Application::ERROR_EXCEPTION: if (!$event->getParam('exception') instanceof NotFoundException) { return; } $viewVariables['reason'] = $event->getParam('exception')->getMessage(); $viewVariables['error'] = 'error-unauthorized'; break; default: return; } $model = new ViewModel($viewVariables); $response = $response ?: new HttpResponse(); $model->setTemplate($this->getTemplate()); $event->getViewModel()->addChild($model); $response->setStatusCode(404); $event->setResponse($response); }
/** * * @param MvcEvent $e */ public function handleError(MvcEvent $e) { $exception = $e->getParam('exception'); $serviceManager = $e->getApplication()->getServiceManager(); $monitor = $serviceManager->get('DwsMonitor\Service\MonitorService'); if (is_object($exception)) { $monitor->err( $exception->getMessage(), [ 'file' => $exception->getFile(), 'line_nr' => $exception->getLine(), 'trace' => $exception->getTraceAsString(), ] ); } else { $monitor->err( $e->getError(), [ 'file' => __FILE__, 'line_nr' => 0, 'trace' => '', ] ); } }
/** * 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); // } }
/** * Sets a specific view template if social network login is unconfigured. * * @param MvcEvent $e */ public function onDispatchError(MvcEvent $e) { $ex = $e->getParam('exception'); $model = $e->getResult(); if ($model instanceof ViewModel && Application::ERROR_EXCEPTION == $e->getError() && 0 === strpos($ex->getMessage(), 'Your application id and secret')) { $model->setTemplate('auth/error/social-profiles-unconfigured'); } }
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); }
/** * Updates the event result with an error object (SerializedJsonModel), * * @param MvcEvent $evt */ public function prepareExceptionViewModel(MvcEvent $evt) { $errorName = $evt->getError(); if (empty($errorName)) { return; } $errorObj = $evt->getResult() instanceof ViewModel ? $evt->getResult()->getVariable('exception') : null; $this->updateEventWithError($evt, $errorObj, $errorName); }