public function handle(Event $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return false; } $exception = $event->getParameter('exception'); if (null !== $this->logger) { $this->logger->err(sprintf('%s: %s (uncaught exception)', get_class($exception), $exception->getMessage())); } else { error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine())); } $class = $this->container->getParameter('exception_manager.class'); $logger = $this->container->has('logger.debug') ? $this->container->get('logger.debug') : null; $attributes = array('_controller' => $this->controller, 'manager' => new $class($exception, $event->getParameter('request'), $logger)); $request = $event->getParameter('request')->duplicate(null, null, $attributes); try { $response = $event->getSubject()->handle($request, HttpKernelInterface::SUB_REQUEST, true); } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } return false; } $event->setReturnValue($response); return true; }
public function handle(Event $event) { $request = $event->getParameter('request'); $master = HttpKernelInterface::MASTER_REQUEST === $event->getParameter('request_type'); $this->initializeSession($request, $master); $this->initializeRequestAttributes($request, $master); }
public function handle(Event $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return false; } $exception = $event->getParameter('exception'); $request = $event->getParameter('request'); if (null !== $this->logger) { $this->logger->err(sprintf('%s: %s (uncaught exception)', get_class($exception), $exception->getMessage())); } else { error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine())); } $logger = null !== $this->logger ? $this->logger->getDebugLogger() : null; $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $logger, 'format' => 0 === strncasecmp(PHP_SAPI, 'cli', 3) ? 'txt' : $request->getRequestFormat()); $request = $request->duplicate(null, null, $attributes); try { $response = $event->getSubject()->handle($request, HttpKernelInterface::SUB_REQUEST, true); } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } // re-throw the exception as this is a catch-all throw new \RuntimeException('Exception thrown when handling an exception.', 0, $e); } $event->setReturnValue($response); return true; }
/** * Filters the Response. * * @param Event $event An Event instance * @param Response $response A Response instance */ public function filter(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type') || $response->headers->has('Content-Type')) { return $response; } $request = $event->getParameter('request'); $format = $request->getRequestFormat(); if (null !== $format && ($mimeType = $request->getMimeType($format))) { $response->headers->set('Content-Type', $mimeType); } return $response; }
public function handle(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return $response; } $request = $event->getParameter('request'); if ('3' === substr($response->getStatusCode(), 0, 1) || $response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html') || 'html' !== $request->getRequestFormat() || $request->isXmlHttpRequest()) { return $response; } $response->setContent($this->injectToolbar($request, $response)); return $response; }
/** * Handles security related exceptions. * * @param Event $event An Event instance */ public function handleException(Event $event) { $exception = $event->getParameter('exception'); $request = $event->getParameter('request'); if ($exception instanceof AuthenticationException) { if (null !== $this->logger) { $this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage())); } try { $response = $this->startAuthentication($request, $exception); } catch (\Exception $e) { $event->setParameter('exception', $e); return; } } elseif ($exception instanceof AccessDeniedException) { $token = $this->context->getToken(); if (null === $token || $token instanceof AnonymousToken) { if (null !== $this->logger) { $this->logger->info('Access denied (user is anonymous); redirecting to authentication entry point'); } try { $response = $this->startAuthentication($request, new InsufficientAuthenticationException('Full authentication is required to access this resource.', $token, 0, $exception)); } catch (\Exception $e) { $event->setParameter('exception', $e); return; } } else { if (null !== $this->logger) { $this->logger->info('Access is denied (and user is not anonymous)'); } if (null === $this->errorPage) { return; } $subRequest = Request::create($this->errorPage); $subRequest->attributes->set(SecurityContext::ACCESS_DENIED_ERROR, $exception->getMessage()); try { $response = $event->getSubject()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage())); } $event->setParameter('exception', new \RuntimeException('Exception thrown when handling an exception.', 0, $e)); return; } $response->setStatusCode(403); } } else { return; } $event->setReturnValue($response); return true; }
/** * Handles the core.response event. * * @param Event $event An Event instance * * @return Response $response A Response instance */ public function handleResponse(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return $response; } if (null !== $this->matcher && !$this->matcher->matches($event->getParameter('request'))) { return $response; } if ($this->onlyException && null === $this->exception) { return $response; } $this->profiler->collect($event->getParameter('request'), $response, $this->exception); $this->exception = null; return $response; }
/** * Handles basic authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if (false === ($username = $request->server->get('PHP_AUTH_USER', false))) { return; } if (null !== ($token = $this->securityContext->getToken())) { if ($token->isImmutable()) { return; } if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && (string) $token === $username) { return; } } if (null !== $this->logger) { $this->logger->debug(sprintf('Basic Authentication Authorization header found for user "%s"', $username)); } try { $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->server->get('PHP_AUTH_PW'))); $this->securityContext->setToken($token); } catch (AuthenticationException $failed) { $this->securityContext->setToken(null); if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication request failed: %s', $failed->getMessage())); } if ($this->ignoreFailure) { return; } $event->setReturnValue($this->authenticationEntryPoint->start($request, $failed)); return true; } }
/** * Handles X509 authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if (null !== $this->logger) { $this->logger->debug(sprintf('Checking secure context token: %s', $this->securityContext->getToken())); } list($user, $credentials) = $this->getPreAuthenticatedData($request); if (null !== ($token = $this->securityContext->getToken())) { if ($token->isImmutable()) { return; } if ($token instanceof PreAuthenticatedToken && $token->isAuthenticated() && (string) $token === $user) { return; } } if (null !== $this->logger) { $this->logger->debug(sprintf('Trying to pre-authenticate user "%s"', $user)); } try { $token = $this->authenticationManager->authenticate(new PreAuthenticatedToken($user, $credentials)); if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication success: %s', $token)); } $this->securityContext->setToken($token); } catch (AuthenticationException $failed) { $this->securityContext->setToken(null); if (null !== $this->logger) { $this->logger->debug(sprintf("Cleared security context due to exception: %s", $failed->getMessage())); } } }
public function handle(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return $response; } if ($response->headers->has('X-Debug-Token') && $response->isRedirect() && $this->interceptRedirects) { $response->setContent(sprintf('<html><head></head><body><h1>This Request redirects to<br /><a href="%s">%s</a>.</h1></body></html>', $response->headers->get('location'), $response->headers->get('location'))); $response->setStatusCode(200); $response->headers->delete('Location'); } $request = $event->getParameter('request'); if (!$response->headers->has('X-Debug-Token') || '3' === substr($response->getStatusCode(), 0, 1) || $response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html') || 'html' !== $request->getRequestFormat() || $request->isXmlHttpRequest()) { return $response; } $this->injectToolbar($request, $response); return $response; }
public function handle(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return $response; } $this->profiler->collect($response); return $response; }
/** * Handles anonymous authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if (null !== $this->context->getToken()) { return; } $this->context->setToken(new AnonymousToken($this->key, 'anon.', array())); if (null !== $this->logger) { $this->logger->debug(sprintf('Populated SecurityContext with an anonymous Token')); } }
public function resolve(Event $event) { $request = $event->getParameter('request'); if (HttpKernelInterface::MASTER_REQUEST === $event->getParameter('request_type')) { // set the context even if the parsing does not need to be done // to have correct link generation $this->router->setContext(array('base_url' => $request->getBaseUrl(), 'method' => $request->getMethod(), 'host' => $request->getHost(), 'is_secure' => $request->isSecure())); } if ($request->attributes->has('_controller')) { return; } if (false !== ($parameters = $this->router->match($request->getPathInfo()))) { if (null !== $this->logger) { $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], str_replace("\n", '', var_export($parameters, true)))); } $request->attributes->replace($parameters); } elseif (null !== $this->logger) { $this->logger->err(sprintf('No route found for %s', $request->getPathInfo())); } }
/** * Handles security. * * @param Event $event An Event instance */ public function handle(Event $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return; } $request = $event->getParameter('request'); $this->dispatcher->disconnect('core.security'); list($listeners, $exception) = $this->map->getListeners($request); if (null !== $exception) { $exception->register($this->dispatcher); } foreach ($listeners as $listener) { $listener->register($this->dispatcher); } $e = $this->dispatcher->notifyUntil(new Event($request, 'core.security', array('request' => $request))); if ($e->isProcessed()) { $event->setReturnValue($e->getReturnValue()); return true; } return; }
/** * * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if ($this->logoutPath !== $request->getPathInfo()) { return; } $this->securityContext->setToken(null); $request->getSession()->invalidate(); $response = new Response(); $response->setRedirect(0 !== strpos($this->targetUrl, 'http') ? $request->getUriForPath($this->targetUrl) : $this->targetUrl, 302); $event->setReturnValue($response); return true; }
/** * Handles digest authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if (!($header = $request->server->get('PHP_AUTH_DIGEST'))) { return; } if (null !== ($token = $this->securityContext->getToken())) { if ($token->isImmutable()) { return; } if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && (string) $token === $username) { return; } } if (null !== $this->logger) { $this->logger->debug(sprintf('Digest Authorization header received from user agent: %s', $header)); } $digestAuth = new DigestData($header); try { $digestAuth->validateAndDecode($this->authenticationEntryPoint->getKey(), $this->authenticationEntryPoint->getRealmName()); } catch (BadCredentialsException $e) { $this->fail($request, $e); return; } try { $user = $this->provider->loadUserByUsername($digestAuth->getUsername()); if (null === $user) { throw new AuthenticationServiceException('AuthenticationDao returned null, which is an interface contract violation'); } $serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod()); } catch (UsernameNotFoundException $notFound) { $this->fail($request, new BadCredentialsException(sprintf('Username %s not found.', $digestAuth->getUsername()))); return; } if ($serverDigestMd5 !== $digestAuth->getResponse()) { if (null !== $this->logger) { $this->logger->debug(sprintf("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", $serverDigestMd5, $digestAuth->getResponse())); } $this->fail($request, new BadCredentialsException('Incorrect response')); return; } if ($digestAuth->isNonceExpired()) { $this->fail($request, new NonceExpiredException('Nonce has expired/timed out.')); return; } if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication success for user "%s" with response "%s"', $digestAuth->getUsername(), $digestAuth->getResponse())); } $this->securityContext->setToken(new UsernamePasswordToken($user, $user->getPassword())); }
/** * Handles form based authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if ($this->options['check_path'] !== $request->getPathInfo()) { return; } try { if (null === ($token = $this->attemptAuthentication($request))) { return; } $response = $this->onSuccess($request, $token); } catch (AuthenticationException $failed) { $response = $this->onFailure($request, $failed); } $event->setReturnValue($response); return true; }
/** * Writes the SecurityContext to the session. * * @param Event $event An Event instance */ public function write(Event $event, Response $response) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) { return $response; } if (null === ($token = $this->context->getToken())) { return $response; } if (null === $token || $token instanceof AnonymousToken) { return $response; } if (null !== $this->logger) { $this->logger->debug('Write SecurityContext in the session'); } $event->getParameter('request')->getSession()->set('_security', serialize($token)); return $response; }
/** * Handles access authorization. * * @param Event $event An Event instance */ public function handle(Event $event) { if (null === ($token = $this->context->getToken())) { throw new AuthenticationCredentialsNotFoundException('A Token was not found in the SecurityContext.'); } $request = $event->getParameter('request'); list($attributes, $channel) = $this->map->getPatterns($request); if (null === $attributes) { return; } if (!$token->isAuthenticated()) { $token = $this->authManager->authenticate($token); $this->context->setToken($token); } if (!$this->accessDecisionManager->decide($token, $attributes, $request)) { throw new AccessDeniedException('Access is denied.'); } }
/** * Handles channel management. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); list($attributes, $channel) = $this->map->getPatterns($request); if ('https' === $channel && !$request->isSecure()) { if (null !== $this->logger) { $this->logger->debug('Redirecting to HTTPS'); } $event->setReturnValue($this->authenticationEntryPoint->start($request)); return true; } if ('http' === $channel && $request->isSecure()) { if (null !== $this->logger) { $this->logger->debug('Redirecting to HTTP'); } $event->setReturnValue($this->authenticationEntryPoint->start($request)); return true; } }
/** * Handles digest authentication. * * @param Event $event An Event instance */ public function handle(Event $event) { $request = $event->getParameter('request'); if (!$request->get($this->usernameParameter)) { return; } if ('_exit' === $request->get($this->usernameParameter)) { $this->securityContext->setToken($this->attemptExitUser($request)); } else { try { $this->securityContext->setToken($this->attemptSwitchUser($request)); } catch (AuthenticationException $e) { if (null !== $this->logger) { $this->logger->debug(sprintf('Switch User failed: "%s"', $e->getMessage())); } } } $response = new Response(); $request->server->set('QUERY_STRING', ''); $response->setRedirect($request->getUri(), 302); $event->setReturnValue($response); return true; }
/** * Print string to console on `behat.output.write` event. * * @param Event $event event */ public function write(Event $event) { $ending = $event->getParameter('newline') ? "\n" : ''; if (!empty($this->outputPath)) { if ($event->hasParameter('file')) { if (!is_dir($dir = $this->outputPath)) { throw new \InvalidArgumentException(sprintf('Directory path expected as --out, but %s given', $dir)); } file_put_contents($dir . '/' . $event->getParameter('file'), $event->getParameter('string') . $ending); } else { file_put_contents($this->outputPath, $event->getParameter('string') . $ending, \FILE_APPEND); } } else { if ($event->hasParameter('file')) { throw new \InvalidArgumentException(sprintf('You *must* specify --out DIR for the %s formatter', $this->formatter)); } $this->output->write($event->getParameter('string'), $event->getParameter('newline'), 1); } }
/** * Listen to `step.run` and find/call proper step definition. * * @param Event $event step event * * @throws Everzet\Behat\Exception\BehaviorException */ public function runStep(Event $event) { $definition = $this->findDefinition($event->getSubject()); $definition->run($event->getParameter('world')); }
/** * Listen to `step.run.after` event & print step run information. * * @param Event $event notified event */ public function printStep(Event $event) { $step = $event->getSubject(); if (!$step->getParent() instanceof BackgroundNode || !$this->backgroundPrinted) { if (!$step->getParent() instanceof OutlineNode || !$this->outlineStepsPrinted) { // Get step description $text = $this->outlineStepsPrinted ? $step->getText() : $step->getCleanText(); $printableText = $text; $description = sprintf(' %s %s', $step->getType(), $text); // Colorize arguments if (null !== $event->getParameter('definition') && StepTester::UNDEFINED !== $event->getParameter('result')) { $argStartCode = $this->colorizeStart($event->getParameter('result') + 10); $argFinishCode = $this->colorizeFinish() . $this->colorizeStart($event->getParameter('result')); $printableText = preg_replace_callback($event->getParameter('definition')->getRegex(), function ($matches) use($argStartCode, $argFinishCode) { $text = array_shift($matches); foreach ($matches as $match) { $text = strtr($text, array('"' . $match . '"' => '"' . $argStartCode . $match . $argFinishCode . '"', '\'' . $match . '\'' => '\'' . $argStartCode . $match . $argFinishCode . '\'', ' ' . $match . ' ' => ' ' . $argStartCode . $match . $argFinishCode . ' ', ' ' . $match => ' ' . $argStartCode . $match . $argFinishCode, $match . ' ' => $argStartCode . $match . $argFinishCode . ' ')); } return $text; }, $printableText); } // Print step description $printableDescription = sprintf(' %s %s', $step->getType(), $printableText); $this->write($printableDescription, $event->getParameter('result'), false); // Print definition path if found one if (null !== $event->getParameter('definition')) { $this->printLineSourceComment(mb_strlen($description), $event->getParameter('definition')->getFile(), $event->getParameter('definition')->getLine()); } else { $this->write(); } // print step arguments if ($step->hasArguments()) { foreach ($step->getArguments() as $argument) { if ($argument instanceof PyStringNode) { $this->write($this->getPyString($argument, 6), $event->getParameter('result')); } elseif ($argument instanceof TableNode) { $this->write($this->getTableString($argument, 6), $event->getParameter('result')); } } } // Print step exception if (null !== $event->getParameter('exception')) { if ($this->verbose) { $error = (string) $event->getParameter('exception'); } else { $error = $event->getParameter('exception')->getMessage(); } $this->write(' ' . strtr($error, array("\n" => "\n ")), $event->getParameter('result')); } } else { if (null !== $event->getParameter('exception')) { $this->outlineSubresultExceptions[] = $event->getParameter('exception'); } } } }
/** * Listen to `step.run.after` event & collect step information. * * @param Event $event notified event */ public function handleStep(Event $event) { $step = $event->getSubject(); if (null !== $event->getParameter('exception')) { $this->scenarioExceptions[] = $event->getParameter('exception'); } }
/** * Listen to `step.run.after` event & print step run information. * * @param Event $event notified event */ public function printStep(Event $event) { $step = $event->getSubject(); if (!$step->getParent() instanceof BackgroundNode || !$this->backgroundPrinted) { if (!$step->getParent() instanceof OutlineNode || !$this->outlineStepsPrinted) { $this->html .= '<li class="' . $this->statuses[$event->getParameter('result')] . '">'; // Get step description $text = htmlspecialchars($this->outlineStepsPrinted ? $step->getText() : $step->getCleanText()); // Print step $this->html .= '<div class="step">'; $this->html .= '<span class="keyword">' . $step->getType() . '</span> '; $this->html .= '<span class="text">' . $text . '</span>'; if (null !== ($def = $event->getParameter('definition'))) { $this->html .= $this->getSourcePathHtml($def->getFile(), $def->getLine()); } $this->html .= '</div>'; // Print step arguments if ($step->hasArguments()) { foreach ($step->getArguments() as $argument) { if ($argument instanceof PyStringNode) { $this->html .= '<pre class="argument">' . htmlspecialchars($argument) . '</pre>'; } elseif ($argument instanceof TableNode) { $this->html .= $this->getTableHtml($argument, 'argument'); } } } // Print step exception if (null !== $event->getParameter('exception')) { $message = $event->getParameter('exception')->getMessage(); $this->html .= '<div class="backtrace"><pre>' . htmlspecialchars($message) . '</pre></div>'; } // Print step snippet if (null !== $event->getParameter('snippet')) { $snippets = array_values($event->getParameter('snippet')); $snippet = $snippets[0]; $this->html .= '<div class="snippet"><pre>' . htmlspecialchars($snippet) . '</pre></div>'; } $this->html .= '</li>'; } else { if (null !== $event->getParameter('exception')) { $this->outlineSubresultExceptions[] = $event->getParameter('exception'); } } } }
/** * Print step information (filepath, fileline, exception description). * * @param Event $event step event * @param string $type information type (pending/failed etc.) */ protected function printStepEventInformation(Event $event, $type) { $step = $event->getSubject(); // Print step information $description = $this->colorize(sprintf(" In step `%s %s'.", $step->getType(), $step->getText()), $type); $this->maxDescriptionLength = $this->maxDescriptionLength > mb_strlen($description) ? $this->maxDescriptionLength : mb_strlen($description); $this->write($description, null, false); if (null !== $event->getParameter('definition')) { $this->printLineSourceComment(mb_strlen($description), $event->getParameter('definition')->getFile(), $event->getParameter('definition')->getLine()); } else { $this->write(); } // Print scenario information $item = $step->getParent(); if ($item instanceof BackgroundNode) { $description = $this->colorize(' From scenario background.', $type); } elseif ($item instanceof ScenarioNode) { $description = $this->colorize(sprintf(" From scenario %s.", $item->getTitle() ? sprintf("`%s'", $item->getTitle()) : '***'), $type); } $this->maxDescriptionLength = $this->maxDescriptionLength > mb_strlen($description) ? $this->maxDescriptionLength : mb_strlen($description); $this->write($description, null, false); $this->printLineSourceComment(mb_strlen($description), $item->getFile(), $item->getLine()); $this->write(); }