public function handle(EventInterface $event)
 {
     $request = $event->get('request');
     $master = HttpKernelInterface::MASTER_REQUEST === $event->get('request_type');
     $this->initializeSession($request, $master);
     $this->initializeRequestAttributes($request, $master);
 }
 public function handle(EventInterface $event)
 {
     static $handling;
     if (true === $handling) {
         return false;
     }
     $handling = true;
     $exception = $event->get('exception');
     $request = $event->get('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) {
         $message = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage());
         if (null !== $this->logger) {
             $this->logger->err($message);
         } else {
             error_log($message);
         }
         // re-throw the exception as this is a catch-all
         throw $exception;
     }
     $event->setProcessed();
     $handling = false;
     return $response;
 }
Esempio n. 3
0
    /**
     * Handles digest authentication.
     *
     * @param EventInterface $event An EventInterface instance
     */
    public function handle(EventInterface $event)
    {
        $request = $event->get('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()));
                }
            }
        }

        $request->server->set('QUERY_STRING', '');
        $response = new RedirectResponse($request->getUri(), 302);

        $event->setProcessed();

        return $response;
    }
Esempio n. 4
0
    /**
     * Performs the logout if requested
     *
     * @param EventInterface $event An EventInterface instance
     */
    public function handle(EventInterface $event)
    {
        $request = $event->get('request');

        if ($this->logoutPath !== $request->getPathInfo()) {
            return;
        }

        if (null !== $this->successHandler) {
            $response = $this->successHandler->onLogoutSuccess($event, $request);

            if (!$response instanceof Response) {
                throw new \RuntimeException('Logout Success Handler did not return a Response.');
            }
        } else {
            $response = new RedirectResponse(0 !== strpos($this->targetUrl, 'http') ? $request->getUriForPath($this->targetUrl) : $this->targetUrl, 302);
        }

        // handle multiple logout attempts gracefully
        if ($token = $this->securityContext->getToken()) {
            foreach ($this->handlers as $handler) {
                $handler->logout($request, $response, $token);
            }
        }

        $this->securityContext->setToken(null);

        $event->setProcessed();

        return $response;
    }
 /**
  * Handles X509 authentication.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     $request = $event->get('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, $this->providerKey));
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Authentication success: %s', $token));
         }
         $this->securityContext->setToken($token);
         if (null !== $this->eventDispatcher) {
             $this->eventDispatcher->notify(new Event($this, 'security.interactive_login', array('request' => $request, 'token' => $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()));
         }
     }
 }
 /**
  * Handles basic authentication.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     $request = $event->get('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->providerKey));
         $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->setProcessed();
         return $this->authenticationEntryPoint->start($event, $request, $failed);
     }
 }
 /**
  * Handles security related exceptions.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handleException(EventInterface $event)
 {
     $exception = $event->get('exception');
     $request = $event->get('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($event, $request, $exception);
         } catch (\Exception $e) {
             $event->set('exception', $e);
             return;
         }
     } elseif ($exception instanceof AccessDeniedException) {
         $token = $this->context->getToken();
         if (!$this->authenticationTrustResolver->isFullFledged($token)) {
             if (null !== $this->logger) {
                 $this->logger->info('Access denied (user is not fully authenticated); redirecting to authentication entry point');
             }
             try {
                 $response = $this->startAuthentication($event, $request, new InsufficientAuthenticationException('Full authentication is required to access this resource.', $token, 0, $exception));
             } catch (\Exception $e) {
                 $event->set('exception', $e);
                 return;
             }
         } else {
             if (null !== $this->logger) {
                 $this->logger->info('Access is denied (and user is neither anonymous, nor remember-me)');
             }
             try {
                 if (null !== $this->accessDeniedHandler) {
                     $response = $this->accessDeniedHandler->handle($event, $request, $exception);
                     if (!$response instanceof Response) {
                         return;
                     }
                 } else {
                     if (null === $this->errorPage) {
                         return;
                     }
                     $subRequest = Request::create($this->errorPage);
                     $subRequest->attributes->set(SecurityContext::ACCESS_DENIED_ERROR, $exception->getMessage());
                     $response = $event->getSubject()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
                     $response->setStatusCode(403);
                     return $response;
                 }
             } 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->set('exception', new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
                 return;
             }
         }
     } else {
         return;
     }
     $event->setProcessed();
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function start(EventInterface $event, Request $request, AuthenticationException $authException = null)
 {
     if ($this->useForward) {
         return $event->getSubject()->handle(Request::create($this->loginPath), HttpKernelInterface::SUB_REQUEST);
     }
     return new RedirectResponse(0 !== strpos($this->loginPath, 'http') ? $request->getUriForPath($this->loginPath) : $this->loginPath, 302);
 }
Esempio n. 9
0
 /**
  * Handles security.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
         return;
     }
     $request = $event->get('request');
     // disconnect all listeners from core.security to avoid the overhead
     // of most listeners having to do this manually
     $this->dispatcher->disconnect('core.security');
     // ensure that listeners disconnect from wherever they have connected to
     foreach ($this->currentListeners as $listener) {
         $listener->unregister($this->dispatcher);
     }
     // register listeners for this firewall
     list($listeners, $exception) = $this->map->getListeners($request);
     if (null !== $exception) {
         $exception->register($this->dispatcher);
     }
     foreach ($listeners as $listener) {
         $listener->register($this->dispatcher);
     }
     // save current listener instances
     $this->currentListeners = $listeners;
     if (null !== $exception) {
         $this->currentListeners[] = $exception;
     }
     // initiate the listener chain
     $ret = $this->dispatcher->notifyUntil($securityEvent = new Event($request, 'core.security', array('request' => $request)));
     if ($securityEvent->isProcessed()) {
         $event->setProcessed();
         return $ret;
     }
 }
Esempio n. 10
0
    /**
     * Handles remember-me cookie based authentication.
     *
     * @param Event $event An Event instance
     */
    public function handle(EventInterface $event)
    {
        if (null !== $this->securityContext->getToken()) {
            return;
        }

        $request = $event->get('request');
        if (null === $token = $this->rememberMeServices->autoLogin($request)) {
            return;
        }

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

            if (null !== $this->eventDispatcher) {
                $this->eventDispatcher->notify(new Event($this, 'security.interactive_login', array('request' => $request, 'token' => $token)));
            }

            if (null !== $this->logger) {
                $this->logger->debug('SecurityContext populated with remember-me token.');
            }
        } catch (AuthenticationException $failed) {
            if (null !== $this->logger) {
                $this->logger->debug(
                    'SecurityContext not populated with remember-me token as the'
                   .' AuthenticationManager rejected the AuthenticationToken returned'
                   .' by the RememberMeServices: '.$failed->getMessage()
                );
            }

            $this->rememberMeServices->loginFail($request);
        }
    }
Esempio n. 11
0
    /**
     * Handles channel management.
     *
     * @param EventInterface $event An EventInterface instance
     */
    public function handle(EventInterface $event)
    {
        $request = $event->get('request');

        list($attributes, $channel) = $this->map->getPatterns($request);

        if ('https' === $channel && !$request->isSecure()) {
            if (null !== $this->logger) {
                $this->logger->debug('Redirecting to HTTPS');
            }

            $event->setProcessed();

            return $this->authenticationEntryPoint->start($event, $request);
        }

        if ('http' === $channel && $request->isSecure()) {
            if (null !== $this->logger) {
                $this->logger->debug('Redirecting to HTTP');
            }

            $event->setProcessed();

            return $this->authenticationEntryPoint->start($event, $request);
        }
    }
Esempio n. 12
0
 /**
  * Filters the Response.
  *
  * @param EventInterface $event    An EventInterface instance
  * @param Response       $response A Response instance
  */
 public function filter(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type') || null === $this->esi) {
         return $response;
     }
     $this->esi->addSurrogateControl($response);
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function filter(EventInterface $event, $value)
 {
     foreach ($this->getListeners($event->getName()) as $listener) {
         if (is_array($listener) && is_string($listener[0])) {
             $listener[0] = $this->container->get($listener[0]);
         }
         $value = call_user_func($listener, $event, $value);
     }
     return $value;
 }
Esempio n. 14
0
 /**
  * Checks if session was initialized and saves if current request is master
  * Runs on 'core.response' in test environment
  *
  * @param EventInterface $event
  * @param Response $response
  *
  * @return Response
  */
 public function filter(EventInterface $event, Response $response)
 {
     if ($request = $event->get('request')) {
         if (HttpKernelInterface::MASTER_REQUEST === $event->get('request_type')) {
             if ($session = $request->getSession()) {
                 $session->save();
             }
         }
     }
     return $response;
 }
 /**
  * Filters the Response.
  *
  * @param EventInterface $event    An EventInterface instance
  * @param Response       $response A Response instance
  */
 public function filter(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type') || $response->headers->has('Content-Type')) {
         return $response;
     }
     $request = $event->get('request');
     $format = $request->getRequestFormat();
     if (null !== $format && ($mimeType = $request->getMimeType($format))) {
         $response->headers->set('Content-Type', $mimeType);
     }
     return $response;
 }
 /**
  * Handles digest authentication.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     $request = $event->get('request');
     if (!($header = $request->server->get('PHP_AUTH_DIGEST'))) {
         return;
     }
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token->isImmutable()) {
             return;
         }
         // FIXME
         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($event, $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($event, $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($event, $request, new BadCredentialsException('Incorrect response'));
         return;
     }
     if ($digestAuth->isNonceExpired()) {
         $this->fail($event, $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(), $this->providerKey));
 }
 /**
  * Handles the core.response event.
  *
  * @param EventInterface $event An EventInterface instance
  *
  * @return Response $response A Response instance
  */
 public function handleResponse(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
         return $response;
     }
     if (null !== $this->matcher && !$this->matcher->matches($event->get('request'))) {
         return $response;
     }
     if ($this->onlyException && null === $this->exception) {
         return $response;
     }
     $this->profiler->collect($event->get('request'), $response, $this->exception);
     $this->exception = null;
     return $response;
 }
 public function handle(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('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="%1$s">%1$s</a>.</h1><h4>The redirect was intercepted by the web debug toolbar to help debugging.<br/>For more information, see the "intercept-redirects" option of the Profiler.</h4></body></html>', $response->headers->get('Location')));
         $response->setStatusCode(200);
         $response->headers->remove('Location');
     }
     $request = $event->get('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($response);
     return $response;
 }
 /**
  * Performs the logout if requested
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     $request = $event->get('request');
     if ($this->logoutPath !== $request->getPathInfo()) {
         return;
     }
     $response = new Response();
     $response->setRedirect(0 !== strpos($this->targetUrl, 'http') ? $request->getUriForPath($this->targetUrl) : $this->targetUrl, 302);
     // handle multiple logout attempts gracefully
     if ($token = $this->securityContext->getToken()) {
         foreach ($this->handlers as $handler) {
             $handler->logout($request, $response, $token);
         }
     }
     $this->securityContext->setToken(null);
     $event->setProcessed();
     return $response;
 }
 /**
  * Handles access authorization.
  *
  * @param EventInterface $event An EventInterface instance
  */
 public function handle(EventInterface $event)
 {
     if (null === ($token = $this->context->getToken())) {
         throw new AuthenticationCredentialsNotFoundException('A Token was not found in the SecurityContext.');
     }
     $request = $event->get('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();
     }
 }
Esempio n. 21
0
    /**
     * Handles security.
     *
     * @param EventInterface $event An EventInterface instance
     */
    public function handle(EventInterface $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
            return;
        }

        // register listeners for this firewall
        list($listeners, $exception) = $this->map->getListeners($event->get('request'));
        if (null !== $exception) {
            $exception->register($this->dispatcher);
        }

        // initiate the listener chain
        foreach ($listeners as $listener) {
            $response = $listener->handle($event);

            if ($event->isProcessed()) {
                return $response;
            }
        }
    }
 /**
  * Update cookies
  * @param Event $event
  */
 public function updateCookies(EventInterface $event, Response $response)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
         return $response;
     }
     if ($this->lastState instanceof TokenInterface) {
         $this->rememberMeServices->loginSuccess($event->get('request'), $response, $this->lastState);
     } else {
         if ($this->lastState instanceof AuthenticationException) {
             $this->rememberMeServices->loginFail($event->get('request'), $response);
         }
     }
     return $response;
 }
Esempio n. 23
0
    /**
     * Writes the SecurityContext to the session.
     *
     * @param EventInterface $event An EventInterface instance
     */
    public function write(EventInterface $event, Response $response)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->get('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->get('request')->getSession()->set('_security_'.$this->contextKey, serialize($token));

        return $response;
    }
 protected function addCall(EventInterface $event, $listener, $type)
 {
     $listener = $this->listenerToString($listener);
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Notified event "%s" to listener "%s" (%s)', $event->getName(), $listener, $type));
     }
     $this->called[$event->getName() . '.' . $listener] = array('event' => $event->getName(), 'caller' => null !== $event->getSubject() ? get_class($event->getSubject()) : null, 'listener' => $listener);
 }
 /**
  * Handles form based authentication.
  *
  * @param Event $event An Event instance
  */
 public function handle(EventInterface $event)
 {
     $request = $event->get('request');
     if (!$this->requiresAuthentication($request)) {
         return;
     }
     try {
         if (null === ($returnValue = $this->attemptAuthentication($request))) {
             return;
         }
         if ($returnValue instanceof TokenInterface) {
             $this->sessionStrategy->onAuthentication($request, $returnValue);
             $response = $this->onSuccess($event, $request, $returnValue);
         } else {
             if ($returnValue instanceof Response) {
                 $response = $returnValue;
             } else {
                 throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
             }
         }
     } catch (AuthenticationException $failed) {
         $response = $this->onFailure($event, $request, $failed);
     }
     $event->setProcessed();
     return $response;
 }
 /**
  * Assigns request and its type on 'core.request' event
  *
  * @param EventInterface $event
  */
 public function handle(EventInterface $event)
 {
     $this->request = $event->get('request');
     $this->master = HttpKernelInterface::MASTER_REQUEST === $event->get('request_type');
 }