Returns a response when is an ajax request and an AccessDeniedException has been thrown

@param GetResponseForExceptionEvent $event

@api
184976
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $request = $event->getRequest();
        $exception = $event->getException();

        if ($request->isXmlHttpRequest()) {
            if ($exception instanceof AccessDeniedException) {
                $token = $this->context->getToken();
                if (!$this->authenticationTrustResolver->isAnonymous($token)) {
                    $event->setResponse(new Response('You haven\'t enough privileges to perform the required action', 403));
                }
            }
        }
    }
1279300
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $exception = $event->getException();
        if (!$exception instanceof ValidationException) {
            return;
        }

        $format = ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);

        $event->setResponse(new Response(
                $this->serializer->serialize($exception->getConstraintViolationList(), $format['key']),
                Response::HTTP_BAD_REQUEST,
                [
                    'Content-Type' => sprintf('%s; charset=utf-8', $format['value'][0]),
                    'X-Content-Type-Options' => 'nosniff',
                    'X-Frame-Options' => 'deny',
                ]
        ));
    }
337612
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        // Should return a error 400 bad request
        if ($exception instanceof ValidationException
         || $exception instanceof SyntaxErrorException) {
            return;
        }

        // Some Exceptions have status code and if 400 it should be handled by them
        if (method_exists($exception, 'getStatusCode')
            && (400 == (int)$exception->getStatusCode())) {
            return;
        }

        $data = $this->decorateKnownCases($exception);

        if (!is_array($data)) {
            $data = [
                'code' => $exception->getCode(),
                'exceptionClass' => get_class($exception),
                'message' => $exception->getMessage()
            ];

            if ($exception->getPrevious() instanceof \Exception) {
                $data['innerMessage'] = $exception->getPrevious()->getMessage();
            }
        }

        if ($this->logger instanceof Logger) {
            $this->logger->critical($exception);
        }

        $response = new JsonResponse($data);
        $event->setResponse($response);
    }
731698
public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $routeName = $request->attributes->get('_route');
        if (!$route = $this->app['routes']->get($routeName)) {
            return;
        }

        foreach ((array) $route->getOption('_before_middlewares') as $callback) {
            $ret = call_user_func($this->app['callback_resolver']->resolveCallback($callback), $request, $this->app);
            if ($ret instanceof Response) {
                $event->setResponse($ret);

                return;
            } elseif (null !== $ret) {
                throw new \RuntimeException(sprintf('A before middleware for route "%s" returned an invalid response value. Must return null or an instance of Response.', $routeName));
            }
        }
    }
567470
public function handle(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        if ($request->getMethod() === Request::METHOD_OPTIONS) {
            $this->getTokenStorage()->setToken(new AnonymousToken('', 'anonymous', []));
            return;
        }

        if (
            !$request->headers->has('Authorization') ||
            !preg_match('/Bearer (.*)/', $request->headers->get('Authorization'))
        ) {
            $token = new AnonymousToken('', 'anonymous');
            $this->getTokenStorage()->setToken($token);
            return;
        }

        $this->doHandle($event);
    }
850397
public function onKernelRequest(GetResponseEvent $event)
    {
        // checks if the backend is secured
        $token = $this->securityContext->getToken();
        if (null !== $token) {

            // Check if the user has already been logged in
            $user = $token->getUser();
            if (null !== $user) {
                $errorMessage = '';
                $userId = $user->getId();

                // Frees the expired locked resources and the resource previously locked
                // by the user
                try {
                    $this->resourcesLocker->unlockExpiredResources();
                    $this->resourcesLocker->unlockUserResource($userId);
                } catch (\PropelException $ex) {
                    $errorMessage = $ex->getMessage();
                }

                if ($errorMessage == '') {
                    $request = $event->getRequest();

                    // LOcks the resource
                    $locked = $request->get('locked');
                    if (null !== $locked) {
                        try {
                            // Process composite locking rules
                            $rules = explode(',', $locked);
                            if (isset($rules[1])) {
                                $locked = $rules[0];
                                $param = $request->get($rules[1]);
                            } else {
                                $param = $request->get($locked);
                            }

                            $key = ('locked' !== $locked) ? $locked . "=" . $param : $request->getUri() . '/locked';
                            $this->resourcesLocker->lockResource($userId, md5($key));
                        } catch (\PropelException $ex) {
                            $errorMessage = 'exception_resource_was_free_but_someone_locked_it';
                        }
                    }
                }

                // The resource is not free, stops the request
                if ($errorMessage != '') {
                    throw new ResourceNotFreeException($errorMessage);
                }
            }
        }
    }
352536
public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();

        // /app_dev.php/contacts?5454
        $requestUri = $request->getRequestUri();

        // /contacts
        $pathInfo = $request->getPathInfo();

        // /app_dev.php
        $baseUrl = $request->getBaseUrl();

        $uri = str_replace($baseUrl, '', $requestUri);

        $em = $this->doctrine->getManager();

        /** @var RedirectRepository $redirectRepository */
        $redirectRepository = $em->getRepository('CompoRedirectBundle:Redirect');

        /** @var Redirect $redirect */
        $redirect = $redirectRepository->findOneBy(
            [
                'urIn' => array_unique([$uri, $pathInfo]),
                'enabled' => true,
            ]
        );

        if ($redirect) {
            $event->setResponse(new RedirectResponse($baseUrl . $redirect->getUrOut(), 301));
            $event->stopPropagation();
        }

        $pageRepository = $em->getRepository(Page::class);

        $lastSlash = mb_substr($pathInfo, -1);

        if ('/' !== $lastSlash) {
            $page = $pageRepository->findOneBy(
                [
                    'url' => [$pathInfo . '/'],
                ]
            );

            if ($page) {
                $event->setResponse(new RedirectResponse($baseUrl . $pathInfo . '/', 301));
                $event->stopPropagation();
            }
        }
    }
1297065
protected function handleBadUserRoleException(GetResponseForExceptionEvent $event, BadUserRoleException $ex) {
        if (null !== $ex->getRedirectUrl()) {
            $event->setResponse(new RedirectResponse($ex->getRedirectUrl()));
        }
        return $event;
    }
1036995
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof NotFoundException) {
            $msg = array("message" => $exception->getMessage());
            // Set status code and content
            $response = $exception->getResponse();
            if (!$response instanceof Response) {
                $response = new Response();
            }

            $response = $response
                ->setStatusCode(Response::HTTP_NOT_FOUND)
                ->setContent($this->getSerializedContent($msg));

            $event->setResponse($response);
        }
    }
8691
public function onKernelRequest(GetResponseEvent $event)
    {
        $url = $event->getRequest()->getRequestUri();
        $token = $this->tokenStorage->getToken();

        if ($token && $this->isAdminToken($this->providerKey, $token) && $this->adminRouteHelper->isAdminRoute($url)) {
            $locale = $token->getUser()->getAdminLocale();

            if (!$locale) {
                $locale = $this->defaultAdminLocale;
            }

            $this->translator->setLocale($locale);
        }
    }
414994
public function onRequest(GetResponseEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }
        $patterns = $this->provider->getPatterns();
        if ($patterns) {
            foreach ($patterns as $pattern) {
                if ($pattern['matcher']->matches($event->getRequest())) {
                   $firewall = $this->provider->getFirewall($pattern['config']);
                   $firewall->handle();
                }
            }
        }
    }
175466
public function onKernelRequest(GetResponseEvent $event): void
    {
        $request = $event->getRequest();
        if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
            return;
        }

        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);

        $isGranted = $resourceMetadata->getOperationAttribute($attributes, 'access_control', null, true);

        if (null === $isGranted) {
            return;
        }

        $extraVariables = $request->attributes->all();
        $extraVariables['object'] = $request->attributes->get('data');
        $extraVariables['request'] = $request;

        if (!$this->resourceAccessChecker->isGranted($attributes['resource_class'], $isGranted, $extraVariables)) {
            throw new AccessDeniedException($resourceMetadata->getOperationAttribute($attributes, 'access_control_message', 'Access Denied.', true));
        }
    }
243156
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (($exception = $event->getException()) instanceof SyntaxErrorException) {
            // Set status code and content
            $response = new Response();
            $response
                ->setStatusCode(Response::HTTP_BAD_REQUEST)
                ->setContent(
                    $this->getSerializedContent(
                        [
                            'message' => sprintf('syntax error in rql: %s', $exception->getMessage())
                        ]
                    )
                );
            $event->setResponse($response);
        }
    }
1002135
public function handle(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        if (!$this->keyExtractor->hasKey($request)) {
            $response = new Response();
            $response->setStatusCode(401);
            $event->setResponse($response);
            return ;
        }

        $apiKey = $this->keyExtractor->extractKey($request);

        $token = new ApiKeyUserToken();
        $token->setApiKey($apiKey);

        try {
            $authToken = $this->authenticationManager->authenticate($token);
            $this->tokenStorage->setToken($authToken);

            return;
        } catch (AuthenticationException $failed) {
            $token = $this->tokenStorage->getToken();
            if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
                $this->tokenStorage->setToken(null);
            }

            $message = $failed->getMessage();
        }

        $response = new Response();
        $response->setContent($message);
        $response->setStatusCode(403);
        $event->setResponse($response);
    }
1304844
public function onKernelException(GetResponseForExceptionEvent $event) {

        $ex = $event->getException();

        // Handle the exception.
        if (true === ($ex instanceof BadUserRoleException)) {
            $this->handleBadUserRoleException($event, $ex);
        }
        if (true === ($ex instanceof RedirectResponseException)) {
            $this->handleRedirectResponseException($event, $ex);
        }

        return $event;
    }
950978
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if (!($event->getRequest())
            || ($this->matchAll === false && !$this->isApiException($exception))
        ) {
            return;
        }

        $data = [];

        if ($this->isApiException($exception)) {
            $exception = $this->exceptionManager->configure($exception);
        }

        $statusCode = $this->getStatusCode($exception);

        $data['error']['status']  = $statusCode;

        if ($code = $exception->getCode()) {
            $data['error']['code'] = $code;
        }

        $data['error']['message'] = $this->getMessage($exception);

        if ($this->isFlattenErrorException($exception)) {
            $data['error']['errors'] = $exception->getFlattenErrors();
        }

        if ($this->stackTrace) {
            $data['error']['stack_trace'] = $exception->getTrace();

            // Clean stacktrace to avoid circular reference or invalid type
            array_walk_recursive(
                $data['error']['stack_trace'],
                function(&$item) {
                    if (is_object($item)) {
                        $item = get_class($item);
                    } elseif (is_resource($item)) {
                        $item = get_resource_type($item);
                    }
                }
            );
        }

        $response = new JsonResponse($data, $statusCode, $this->getHeaders($exception));
        $event->setResponse($response);
    }
330744
public function onCoreException(GetResponseForExceptionEvent $event)
	{
	    $exception = $event->getException();
	    $request = $event->getRequest();

    	if ($request->isXmlHttpRequest()) {
    		$msg = "";
    		if($exception instanceof AccessDeniedException ) {
    			$msg = "User Not Authenticated";
    		} elseif($exception instanceof AuthenticationCredentialsNotFoundException) {
    			$msg = "User Not Allowed";
    		} elseif($exception instanceof AuthenticationException) {
    			// Change this
    			$msg = "User Not Authenticated";
    		}

    		if($msg) {
    			$responseData = array('status' => 403, 'reason' => $msg);
    			$response = new JsonResponse();
    			$response->setData($responseData);
    			$response->setStatusCode($responseData['status']);
    			$event->setResponse($response);
    		}
	    }
	}