setError() 공개 메소드

Set the error message (indicating error in handling request)
public setError ( string $message ) : MvcEvent
$message string
리턴 MvcEvent
 /**
  * @covers ::onDispatchError
  */
 public function testOnDispatchErrorStoreAndStreamImage()
 {
     $id = 'someId';
     $resource = 'someResource';
     $this->event->setError(Application::ERROR_ROUTER_NO_MATCH);
     $image = $this->getMockBuilder(ImageEntity::class)->setMethods(['getLength', 'getResource'])->getMock();
     $image->setId($id);
     $image->setType('image/jpeg');
     $image->setName('image.jpg');
     $image->method('getLength')->willReturn(1024);
     $image->method('getResource')->willReturn($resource);
     $this->manager->expects($this->once())->method('matchUri')->willReturn($id);
     $this->repository->expects($this->once())->method('find')->with($this->equalTo($id))->willReturn($image);
     $this->manager->expects($this->once())->method('store')->with($this->identicalTo($image));
     $this->listener->onDispatchError($this->event);
     $response = $this->event->getResponse();
     $this->assertInstanceOf(Stream::class, $response);
     $this->assertEquals(Response::STATUS_CODE_200, $response->getStatusCode());
     $this->assertEquals($image->getName(), $response->getStreamName());
     $this->assertEquals($image->getResource(), $response->getStream());
     $headers = $response->getHeaders();
     $this->assertInstanceOf(Headers::class, $headers);
     $this->assertTrue($headers->has('Content-Type'));
     $this->assertEquals($image->getType(), $headers->get('Content-Type')->getFieldValue());
     $this->assertTrue($headers->has('Content-Length'));
     $this->assertEquals($image->getLength(), $headers->get('Content-Length')->getFieldValue());
 }
 public function testOnRenderErrorCreatesAnApiProblemResponse()
 {
     $response = new Response();
     $request = new Request();
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     $event = new MvcEvent();
     $event->setError(Application::ERROR_EXCEPTION);
     $event->setRequest($request);
     $event->setResponse($response);
     $this->listener->onRenderError($event);
     $this->assertTrue($event->propagationIsStopped());
     $this->assertSame($response, $event->getResponse());
     $this->assertEquals(406, $response->getStatusCode());
     $headers = $response->getHeaders();
     $this->assertTrue($headers->has('Content-Type'));
     $this->assertEquals('application/problem+json', $headers->get('content-type')->getFieldValue());
     $content = json_decode($response->getContent(), true);
     $this->assertArrayHasKey('status', $content);
     $this->assertArrayHasKey('title', $content);
     $this->assertArrayHasKey('describedBy', $content);
     $this->assertArrayHasKey('detail', $content);
     $this->assertEquals(406, $content['status']);
     $this->assertEquals('Not Acceptable', $content['title']);
     $this->assertContains('www.w3.org', $content['describedBy']);
     $this->assertContains('accept', $content['detail']);
 }
예제 #3
0
 /**
  * @param MvcEvent $e
  */
 public static function onRoute(MvcEvent $e)
 {
     if (!$e->getRequest() instanceof HttpRequest) {
         return;
     }
     $app = $e->getTarget();
     $rbacService = $app->getServiceManager()->get('ZfcRbac\\Service\\Rbac');
     $match = $app->getMvcEvent()->getRouteMatch();
     $controller = $match->getParam('controller');
     $action = $match->getParam('action');
     $resource = sprintf('%s:%s', $controller, $action);
     try {
         if ($rbacService->getFirewall('controller')->isGranted($resource)) {
             return;
         }
     } catch (InvalidArgumentException $ex) {
         //if Exception, default to unauthorized
     }
     try {
         $e->setError($rbacService::ERROR_CONTROLLER_UNAUTHORIZED)->setParam('identity', $rbacService->getIdentity())->setParam('controller', $controller)->setParam('action', $action);
         $app->getEventManager()->trigger('dispatch.error', $e);
     } catch (InvalidArgumentException $ex) {
         return;
     }
 }
예제 #4
0
 public function checkPermission(MvcEvent $e)
 {
     $params = $e->getRouteMatch()->getParams();
     if (!isset($params['backend']) || !$params['backend']) {
         return;
     }
     $serviceLocator = $e->getApplication()->getServiceManager();
     $config = $serviceLocator->get('config');
     if (Authentication::getInstance()->hasIdentity()) {
         // Check if user has permission to access the current page
         $user = Authentication::getInstance()->getIdentity();
         /** @var \Acl\Service\Acl $acl */
         $acl = $serviceLocator->get('Acl\\Service\\Acl');
         if (!$acl->isAllowed($user->role, $params['controller'], $params['action'])) {
             $e->setError(self::ERROR_FORBIDDEN);
             $e->getApplication()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
         }
     } else {
         $request = $e->getRequest();
         /** @var \Zend\Http\Response $response */
         $response = $e->getResponse();
         $router = $e->getRouter();
         $url = $router->assemble([], ['name' => $config['acl']['signin_route']]) . '?continue=' . $request->getUri()->toString();
         $response->getHeaders()->addHeaderLine('Location', $url);
         $response->setStatusCode(302);
         return $response;
     }
 }
예제 #5
0
 public function testOnBootstrapListenersWithHttpRequest()
 {
     $module = new Module();
     $application = $this->createApplication();
     $sm = $application->getServiceManager();
     $sm->setService('FilterManager', new FilterPluginManager());
     foreach ($module->getServiceConfig()['invokables'] as $key => $value) {
         $sm->setInvokableClass($key, $value);
     }
     foreach ($module->getServiceConfig()['factories'] as $key => $value) {
         $sm->setFactory($key, $value);
     }
     $sm->get('ViewHelperManager')->setService('bodyClass', $this->getMock(BodyClass::class));
     $event = new MvcEvent();
     $event->setApplication($application);
     $em = $application->getEventManager();
     $em->getSharedManager()->clearListeners(LayoutUpdater::class);
     $module->onBootstrap($event);
     $layoutUpdater = $sm->get(LayoutUpdaterInterface::class);
     $this->assertEquals(['default'], $layoutUpdater->getHandles());
     $mvcEvent = new MvcEvent();
     $mvcEvent->setApplication($application);
     $mvcEvent->setName(MvcEvent::EVENT_DISPATCH_ERROR);
     $mvcEvent->setError('test-error');
     $em->triggerEvent($mvcEvent);
     $this->assertEquals(['default', 'test-error'], $layoutUpdater->getHandles());
 }
예제 #6
0
 protected function terminateEvent(MvcEvent $event, $error, \Exception $exception)
 {
     $eventManager = $event->getApplication()->getEventManager();
     $event->setError($error);
     $event->setParam('exception', $exception);
     $event->stopPropagation(true);
     $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
 public function testOnError_WithApiException()
 {
     $event = new MvcEvent();
     $event->setError("The resource doesn't support the specified HTTP verb.");
     $event->setParam('exception', new MethodNotAllowedException());
     $event->setResponse(new Response());
     $result = $this->testedObject->onError($event);
     $this->assertInstanceOf(JsonModel::class, $result);
 }
예제 #8
0
 public static function onRoute(MvcEvent $e)
 {
     $app = $e->getTarget();
     $route = $e->getRouteMatch()->getMatchedRouteName();
     $security = $app->getServiceManager()->get('SpiffySecurity\\Service\\Security');
     if (!$security->getFirewall('route')->isGranted($route)) {
         $e->setError($security::ERROR_ROUTE_UNAUTHORIZED)->setParam('identity', $security->getIdentity())->setParam('route', $route);
         $app->getEventManager()->trigger('dispatch.error', $e);
     }
 }
예제 #9
0
 public function onDispatchError(MvcEvent $e)
 {
     if ($e->getError() !== Zf2Application::ERROR_ROUTER_NO_MATCH) {
         return;
     }
     $routeMatch = new RouteMatch(array());
     $routeMatch->setParam('controller', 'Zf1Module\\DispatchController');
     $e->setError(null);
     $e->setRouteMatch($routeMatch);
     return $routeMatch;
 }
예제 #10
0
 /**
  * Capture Error converted to exception, then trigger a dispatch error
  * @param MvcEvent $e
  */
 public function onEvent(MvcEvent $event)
 {
     $exception = ErrorHandler::stop();
     if ($exception instanceof \Exception) {
         $event->setError(Application::ERROR_EXCEPTION);
         $event->setParam('exception', $exception);
         $this->getEventManager()->trigger($event::EVENT_DISPATCH_ERROR, $event);
     } elseif (!$event->getError() && $event->getResponse()->getStatusCode() == 404) {
         $event->setError(Application::ERROR_CONTROLLER_CANNOT_DISPATCH);
         $this->getEventManager()->trigger($event::EVENT_DISPATCH_ERROR, $event);
     }
 }
예제 #11
0
 public static function onRoute(MvcEvent $e)
 {
     $app = $e->getTarget();
     $service = $app->getServiceManager()->get('BjyAuthorize\\Service\\Authorize');
     $match = $app->getMvcEvent()->getRouteMatch();
     $routeName = $match->getMatchedRouteName();
     $allowed = $service->isAllowed('route/' . $routeName);
     if (!$allowed) {
         $e->setError('error-unauthorized-route')->setParam('route', $routeName)->setParam('identity', $service->getIdentity());
         $app->getEventManager()->trigger('dispatch.error', $e);
     }
 }
예제 #12
0
파일: Route.php 프로젝트: Mystraht/builder
 /**
  * @param MvcEvent $e
  */
 public static function onRoute(MvcEvent $e)
 {
     if (!$e->getRequest() instanceof HttpRequest) {
         return;
     }
     $app = $e->getTarget();
     $route = $e->getRouteMatch()->getMatchedRouteName();
     $rbacService = $app->getServiceManager()->get('ZfcRbac\\Service\\Rbac');
     if (!$rbacService->getFirewall('route')->isGranted($route)) {
         $e->setError($rbacService::ERROR_ROUTE_UNAUTHORIZED)->setParam('identity', $rbacService->getIdentity())->setParam('route', $route);
         $app->getEventManager()->trigger('dispatch.error', $e);
     }
 }
예제 #13
0
 public static function onRoute(MvcEvent $e)
 {
     $app = $e->getTarget();
     $service = $app->getServiceManager()->get('BjyAuthorize\\Service\\Authorize');
     $match = $app->getMvcEvent()->getRouteMatch();
     $controller = $match->getParam('controller');
     $action = $match->getParam('action');
     $controllerResource = sprintf('controller/%s', $controller);
     $actionResource = sprintf('controller/%s:%s', $controller, $action);
     $allowed = $service->isAllowed($controllerResource) || $service->isAllowed($actionResource);
     if (!$allowed) {
         $e->setError('error-unauthorized-controller')->setParam('identity', $service->getIdentity())->setParam('controller', $controller)->setParam('action', $action);
         $app->getEventManager()->trigger('dispatch.error', $e);
     }
 }
예제 #14
0
 /**
  * 
  * @param MvcEvent $event
  */
 protected function triggerForbiddenEvent(MvcEvent $event)
 {
     $event->setError('route-forbidden');
     $event->setParam('exception', new UnauthorizedException('You are forbidden!', 403));
     $event->stopPropagation(true);
     if ($this->hasErrorViewModel()) {
         $event->setViewModel($this->errorView);
     }
     $response = $event->getResponse();
     $response->setStatusCode(403);
     $event->setResponse($response);
     $application = $event->getApplication();
     $eventManager = $application->getEventManager();
     $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
예제 #15
0
 public function onRoute(MvcEvent $mvcEvent)
 {
     $request = $mvcEvent->getRequest();
     $response = $mvcEvent->getResponse();
     /**
      * If it's a CLI request - return.
      */
     if ($request instanceof \Zend\Console\Request) {
         return;
     }
     $app = $mvcEvent->getApplication();
     $match = $app->getMvcEvent()->getRouteMatch();
     $routeName = $match->getMatchedRouteName();
     $method = strtolower($request->getMethod());
     if (!$this->acl->hasResource($routeName)) {
         return;
     }
     $role = null;
     /**
      * Infer that if :
      * 1. the request is protected under 2 legged oauth,
      *    then it is a 2 legged oauth request
      * 2. the request is protected under 3 legged oauth,
      *    then it is a 3 legged oauth request
      * 3. otherwise it is not protected
      */
     if ($this->acl->isAllowed(BgOauthProviderAcl::TWO_LEGGED, $routeName, $method)) {
         $role = BgOauthProviderAcl::TWO_LEGGED;
         $this->oauthProvider->is2LeggedEndpoint();
     } elseif ($this->acl->isAllowed(BgOauthProviderAcl::THREE_LEGGED, $routeName, $method)) {
         $role = BgOauthProviderAcl::THREE_LEGGED;
     } else {
         return;
     }
     try {
         $this->oauthProvider->checkOAuthRequest();
     } catch (\OAuthException $e) {
         $error = \OAuthProvider::reportProblem($e, false);
         $response->setStatusCode(Response::STATUS_CODE_401);
         $response->setContent($error);
         $response->getHeaders()->addHeaders(array('WWW-Authenticate' => $error));
         $mvcEvent->setError(self::ERROR);
         $mvcEvent->getApplication()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $mvcEvent);
         return $response;
     }
     //Success!
 }
 /**
  * Listen to the "route" event and attempt to route the request
  *
  * If no matches are returned, triggers "dispatch.error" in order to
  * create a 404 response.
  *
  * Seeds the event with the route match on completion.
  *
  * @param  MvcEvent $e
  * @return null|Router\RouteMatch
  */
 public function onRoute($e)
 {
     $target = $e->getTarget();
     $request = $e->getRequest();
     $router = $e->getRouter();
     $routeMatch = $router->match($request);
     if (!$routeMatch instanceof Router\RouteMatch) {
         $e->setError(Application::ERROR_ROUTER_NO_MATCH);
         $results = $target->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
         if (count($results)) {
             return $results->last();
         }
         return $e->getParams();
     }
     $e->setRouteMatch($routeMatch);
     return $routeMatch;
 }
예제 #17
0
 public static function onRoute(MvcEvent $e)
 {
     $app = $e->getTarget();
     $security = $app->getServiceManager()->get('SpiffySecurity\\Service\\Security');
     $match = $app->getMvcEvent()->getRouteMatch();
     $controller = $match->getParam('controller');
     $action = $match->getParam('action');
     $resource = sprintf('%s:%s', $controller, $action);
     try {
         if (!$security->getFirewall('controller')->isGranted($resource)) {
             $e->setError($security::ERROR_CONTROLLER_UNAUTHORIZED)->setParam('identity', $security->getIdentity())->setParam('controller', $controller)->setParam('action', $action);
             $app->getEventManager()->trigger('dispatch.error', $e);
         }
     } catch (\InvalidArgumentException $e) {
         return;
     }
 }
 /**
  * @param MvcEvent $event
  */
 public function checkDeactivatedUser(MvcEvent $event)
 {
     $routeName = $event->getRouteMatch()->getMatchedRouteName();
     $allowedRoutes = ['auth-logout'];
     // do nothing for allowed routes
     if (in_array($routeName, $allowedRoutes)) {
         return;
     }
     $auth = $event->getApplication()->getServiceManager()->get('AuthenticationService');
     // check for inactive user
     if ($auth->hasIdentity() && !$auth->getUser()->isActive()) {
         // set event error & throw dispach error
         $event->setError('User inactive');
         $event->setParam('exception', new UserDeactivatedException());
         return $event->getTarget()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event)->last();
     }
 }
예제 #19
0
파일: Route.php 프로젝트: kler/BjyAuthorize
 /**
  * Event callback to be triggered on dispatch, causes application error triggering
  * in case of failed authorization check
  *
  * @param MvcEvent $event
  *
  * @return void
  */
 public function onRoute(MvcEvent $event)
 {
     /* @var $service \BjyAuthorize\Service\Authorize */
     $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize');
     $match = $event->getRouteMatch();
     $routeName = $match->getMatchedRouteName();
     if ($service->isAllowed('route/' . $routeName)) {
         return;
     }
     $event->setError(static::ERROR);
     $event->setParam('route', $routeName);
     $event->setParam('identity', $service->getIdentity());
     $event->setParam('exception', new UnauthorizedException('You are not authorized to access ' . $routeName));
     /* @var $app \Zend\Mvc\Application */
     $app = $event->getTarget();
     $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
예제 #20
0
파일: Web.php 프로젝트: fousheezy/auth
 /**
  * @param MvcEvent $e
  *
  * @return mixed
  */
 public function handleNotAllowed(MvcEvent $e)
 {
     // is this user authenticated?
     if (!$this->getCurrentUser()->isNull()) {
         // not allowed to this route by the ACL
         $app = $e->getTarget();
         $route = $e->getRouteMatch();
         $e->setError(self::ACL_ACCESS_DENIED)->setParam('route', $route->getMatchedRouteName());
         $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
         return;
     }
     // redirect to login
     if ($e->getRouteMatch()->getMatchedRouteName() == UserController::ROUTE_LOGIN) {
         // prevent infinite loop
         return $this->triggerStatus($e, Response::STATUS_CODE_403);
     }
     return $this->redirectTo($e, UserController::ROUTE_LOGIN);
 }
 public function testOnDispatchErrorReturnsAnApiProblemResponseBasedOnCurrentEventException()
 {
     $request = new Request();
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     $event = new MvcEvent();
     $event->setError(Application::ERROR_EXCEPTION);
     $event->setParam('exception', new DomainException('triggering exception', 400));
     $event->setRequest($request);
     $return = $this->listener->onDispatchError($event);
     $this->assertTrue($event->propagationIsStopped());
     $this->assertInstanceOf('ZF\\ApiProblem\\ApiProblemResponse', $return);
     $response = $event->getResponse();
     $this->assertSame($return, $response);
     $problem = $response->getApiProblem();
     $this->assertInstanceOf('ZF\\ApiProblem\\ApiProblem', $problem);
     $this->assertEquals(400, $problem->status);
     $this->assertSame($event->getParam('exception'), $problem->detail);
 }
예제 #22
0
 /**
  * @param \Zend\Mvc\MvcEvent $event The MvcEvent instance
  */
 public function onRoute(MvcEvent $event)
 {
     $app = $event->getApplication();
     $serviceManager = $app->getServiceManager();
     $matches = $event->getRouteMatch();
     if ($this->isAdminRoute($matches->getMatchedRouteName())) {
         /** @var AuthenticationServiceInterface $authenticationService */
         $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService');
         if (!$authenticationService->hasIdentity()) {
             $url = $event->getRouter()->assemble(array(), array('name' => 'admin/login', 'query' => array('destination' => $event->getRequest()->getRequestUri())));
             /** @var ResponseInterface $response */
             $response = $event->getResponse();
             $response->getHeaders()->addHeaderLine('Location', $event->getRequest()->getBaseUrl() . $url);
             $response->setStatusCode(302);
             $response->sendHeaders();
             $event->setError('Login required');
         }
     }
 }
 /**
  * Create an exception json 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
     if (!($error = $e->getError())) {
         return;
     }
     // Do nothing if the result is a response object
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     if ($error != Application::ERROR_EXCEPTION) {
         return;
     }
     if (!$e->getRequest() instanceof Request) {
         return;
     }
     $accept = $e->getRequest()->getHeaders()->get('Accept');
     if (!($accept && $accept->match('application/json'))) {
         return;
     }
     if (!($exception = $e->getParam('exception'))) {
         return;
     }
     $modelData = $this->serializeException($exception);
     $e->setResult(new JsonModel($modelData));
     $e->setError(false);
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $status = $response->getStatusCode();
     if (isset($modelData['statusCode']) && !empty($modelData['statusCode'])) {
         $response->setStatusCode($modelData['statusCode']);
     } else {
         if (empty($status) || strval($status)[0] == '2') {
             $response->setStatusCode(500);
         }
     }
     $response->getHeaders()->addHeaders([$accept, ContentType::fromString('Content-type: application/api-problem+json')]);
 }
예제 #24
0
 public function onRoute(MvcEvent $event)
 {
     $err = RouteGuard::ERROR;
     $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize');
     /* @var $match \Zend\Mvc\Router\RouteMatch */
     $match = $event->getRouteMatch();
     $routeName = $match->getMatchedRouteName();
     $privilege = $match->getParam('xelax_admin_privilege');
     $privilegeParts = explode('/', $privilege);
     if (empty($privilege) || array_pop($privilegeParts) == 'subroute' || $service->isAllowed('xelax-route/' . $routeName, $privilege)) {
         return;
     }
     $event->setError($err);
     $event->setParam('route', $routeName);
     $event->setParam('identity', $service->getIdentity());
     $event->setParam('exception', new UnAuthorizedException('You are not authorized to access ' . $routeName));
     /* @var $app \Zend\Mvc\Application */
     $app = $event->getTarget();
     $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
예제 #25
0
 public function onRoute(\Zend\Mvc\MvcEvent $e)
 {
     $request = $e->getRequest();
     if ($request instanceof \Zend\Console\Request) {
         // Do not check ACL for console user
         return;
     }
     $resource = $e->getRouteMatch()->getParam('resource', null);
     $privilege = $e->getRouteMatch()->getParam('privilege', null);
     if (!$this->acl->hasResource($resource)) {
         // Do something if current resource doesn't exist (not registered)
     }
     if ($this->acl->isAllowed($this->getRole(), $resource, $privilege)) {
         return;
     }
     // setForbiddenAccess
     $e->setError('Forbidden Access');
     $e->getResponse()->setStatusCode(403);
     $e->getTarget()->getEventManager()->trigger('dispatch.error', $e);
 }
예제 #26
0
    /**
     * Listen to the "route" event and attempt to route the request
     *
     * If no matches are returned, triggers "dispatch.error" in order to
     * create a 404 response.
     *
     * Seeds the event with the route match on completion.
     * 
     * @param  MvcEvent $e 
     * @return null|Router\RouteMatch
     */
    public function onRoute($e)
    {
        $target     = $e->getTarget();
        $request    = $e->getRequest();
        $router     = $e->getRouter();
        $routeMatch = $router->match($request);

        if (!$routeMatch instanceof Router\RouteMatch) {
            $e->setError($target::ERROR_ROUTER_NO_MATCH);

            $results = $target->events()->trigger('dispatch.error', $e);
            if (count($results)) {
                $return  = $results->last();
            } else {
                $return = $e->getParams();
            }
            return $return;
        }

        $e->setRouteMatch($routeMatch);
        return $routeMatch;
    }
예제 #27
0
 /**
  * @param MvcEvent $e
  */
 public function onBootstrap(MvcEvent $e)
 {
     ini_set('display_errors', 'off');
     $errorCallback = function () use($e) {
         // Fetching the error's information
         $error = error_get_last() ?: func_get_args();
         $error = array_values($error);
         if (!$error) {
             return;
         }
         // Create exception ans associated event
         $exception = new ErrorException($error[1], 0, $error[0], $error[2], $error[3], isset($error[4]) && $error[4] instanceof \Exception ? $error[4] : null);
         $e->setParam('exception', $exception);
         $e->setError(Application::ERROR_EXCEPTION);
         $e->setName(MvcEvent::EVENT_RENDER_ERROR);
         /** @var Application $application */
         $application = $e->getApplication();
         $application->getEventManager()->triggerEvent($e);
     };
     // Set error handlers
     set_error_handler($errorCallback, \E_ALL);
     register_shutdown_function($errorCallback);
 }
예제 #28
0
 /**
  * Event callback to be triggered on dispatch, causes application error triggering
  * in case of failed authorization check
  *
  * @param MvcEvent $event
  *
  * @return void
  */
 public function onDispatch(MvcEvent $event)
 {
     /* @var $service \BjyAuthorize\Service\Authorize */
     $service = $this->serviceLocator->get('BjyAuthorize\\Service\\Authorize');
     $match = $event->getRouteMatch();
     $controller = $match->getParam('controller');
     $action = $match->getParam('action');
     $request = $event->getRequest();
     $method = $request instanceof HttpRequest ? strtolower($request->getMethod()) : null;
     $authorized = $service->isAllowed($this->getResourceName($controller)) || $service->isAllowed($this->getResourceName($controller, $action)) || $method && $service->isAllowed($this->getResourceName($controller, $method));
     if ($authorized) {
         return;
     }
     $event->setError(static::ERROR);
     $event->setParam('identity', $service->getIdentity());
     $event->setParam('controller', $controller);
     $event->setParam('action', $action);
     $errorMessage = sprintf("You are not authorized to access %s:%s", $controller, $action);
     $event->setParam('exception', new UnAuthorizedException($errorMessage));
     /* @var $app \Zend\Mvc\ApplicationInterface */
     $app = $event->getTarget();
     $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
예제 #29
0
파일: Guard.php 프로젝트: srayner/civaccess
 public function onDispatch(MvcEvent $event)
 {
     $app = $event->getTarget();
     $aclService = $this->serviceLocator->get('CivAccess\\AclService');
     $authService = $this->serviceLocator->get('CivAccess\\AuthService');
     $match = $event->getRouteMatch();
     $resource = $match->getParam('controller');
     $privilege = $match->getParam('action');
     // Check access.
     $role = $authService->hasIdentity() ? (string) $authService->getIdentity()->getId() : 'guest';
     $authorized = $aclService->isAllowed($role, $resource, $privilege);
     // If authorized, no action is required.
     if ($authorized) {
         return;
     }
     // If not authorized, setup an exception and trigger a dispatch error.
     $errorMessage = sprintf("You are not authorized to access %s:%s", $resource, $privilege);
     $event->setError(static::ERROR);
     $event->setParam('role', $role);
     $event->setParam('resource', $resource);
     $event->setParam('privilege', $privilege);
     $event->setParam('exception', new UnAuthorizedException($errorMessage));
     $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
예제 #30
0
 public function handleError(MvcEvent $e)
 {
     if ($e->getError() == Application::ERROR_ROUTER_NO_MATCH) {
         return;
     }
     if ($e->getError() == Application::ERROR_EXCEPTION) {
         $translator = $e->getApplication()->getServiceManager()->get('translator');
         $exception = $e->getParam('exception');
         if ($exception instanceof BusinessException) {
             // translate
             $status = intval($exception->getCode());
             $messsage = $translator->translate($exception->getMessage());
         } else {
             $status = 999;
             if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER['APPLICATION_ENV'] == 'development') {
                 $messsage = $exception->getMessage();
             } else {
                 $messsage = '对不起, 系统出错了...';
             }
         }
         /* @var $request \Zend\Http\Request */
         $request = $e->getRequest();
         $response = $e->getResponse();
         if ($request->isXmlHttpRequest()) {
             // change status code from 500 to 200
             $response->setStatusCode(200);
             $response->getHeaders()->addHeaders(array('Content-type' => 'application/json; charset=utf8'));
             $json = new JsonModel();
             $json->setVariables(array('status' => $status, 'message' => $messsage, 'content' => array()));
             $json->setTerminal(false);
             $e->setViewModel($json);
             // mute other default exception handler
             $e->setError(false);
         }
     }
 }