setResponse() public method

Sets a response and stops event propagation
public setResponse ( Response $response )
$response Symfony\Component\HttpFoundation\Response
 /**
  * Determine whether the page is configured to be offline.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function onKernelRequestMaintenance(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $route_match = RouteMatch::createFromRequest($request);
     $path = $request->attributes->get('_system_path');
     if ($this->maintenanceMode->applies($route_match)) {
         // If the site is offline, log out unprivileged users.
         if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
             user_logout();
             // Redirect to homepage.
             $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
             return;
         }
     }
     if ($this->account->isAuthenticated()) {
         if ($path == 'user/login') {
             // If the user is already logged in, redirect to their profile page.
             $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()]));
             return;
         }
         if ($path == 'user/register') {
             // If the user is already registered, redirect to their edit page.
             $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
             return;
         }
     }
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     //find out if the current request contains any information by which the user might be authenticated
     if (!$request->headers->has('X-WSSE')) {
         return;
     }
     $ae_message = null;
     $this->wsseHeader = $request->headers->get('X-WSSE');
     $wsseHeaderInfo = $this->parseHeader();
     if ($wsseHeaderInfo !== false) {
         $token = new Token();
         $token->setUser($wsseHeaderInfo['Username']);
         $token->setAttribute('digest', $wsseHeaderInfo['PasswordDigest']);
         $token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
         $token->setAttribute('created', $wsseHeaderInfo['Created']);
         try {
             $returnValue = $this->authenticationManager->authenticate($token);
             if ($returnValue instanceof TokenInterface) {
                 return $this->securityContext->setToken($returnValue);
             } else {
                 if ($returnValue instanceof Response) {
                     return $event->setResponse($returnValue);
                 }
             }
         } catch (AuthenticationException $ae) {
             $event->setResponse($this->authenticationEntryPoint->start($request, $ae));
         }
     }
 }
 /**
  * 请求完成后执行
  */
 public function onRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $request = $event->getRequest();
     $session = $request->getSession();
     // 如果有 OpenID,则放行
     if ($session->has('openid')) {
         return;
     }
     // 排除资源文件
     if (preg_match("^/(_(profiler|wdt)|css|images|js)/^", $request->getPathInfo())) {
         return;
     }
     // 排除不需要 openid 的 URL
     $currentRoute = $request->get('_route');
     $currentParams = $request->get('_route_params');
     if (in_array($currentRoute, $this->ignoreRoute)) {
         return;
     }
     // 跳转到授权页,并把当前页作为参数(授权完成后还要跳转回来)
     $currentUri = $this->router->generate($currentRoute, $currentParams);
     $authorizeUrl = $this->router->generate('wechat_authorize', ['continue' => $currentUri]);
     if (!$request->isXmlHttpRequest()) {
         return $event->setResponse(new RedirectResponse($authorizeUrl));
     }
     $response = new JsonResponse(['failure' => '401 Unauthorized', 'redirect' => $authorizeUrl]);
     return $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     try {
         $response = $this->authenticationManager->authenticate(new WordpressToken());
         if ($response->isAuthenticated()) {
             $this->securityContext->setToken($response);
             $session = $request->getSession();
             $token_id = uniqid();
             $session->set('token_id', $token_id);
             $session->set($token_id, $response);
         } elseif ($response->getRedirectUrl() != null) {
             $url = $response->getRedirectUrl();
             if (strpos('?', $url) !== false) {
                 $separator = '&';
             } else {
                 $separator = '?';
             }
             $url .= $separator . 'redirect_to=' . urlencode($request->getUri());
             $response = new RedirectResponse($url);
             $event->setResponse($response);
         } else {
             $response = new Response();
             $response->setStatusCode(403);
             $event->setResponse($response);
         }
     } catch (AuthenticationException $e) {
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
     }
 }
示例#5
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($this->kernel->getEnvironment() != "dev") {
         if (preg_match("/\\/api\\//", $event->getRequest()->getUri())) {
             $requestUri = $event->getRequest()->getUri();
             $requestMethod = $event->getRequest()->getMethod();
             if ($requestMethod !== "GET") {
                 $token = $this->context->getToken();
                 if (isset($token)) {
                     $user = $token->getUser();
                     if (!isset($user) || "anon." === $user) {
                         if (!$event->getRequest()->query->has('api_key')) {
                             $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
                         }
                     }
                 } else {
                     $event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
                 }
             }
         }
     }
     $request = $event->getRequest();
     if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE'))) {
         $contentType = $request->headers->get('Content-Type');
         $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
         if (!$this->decoderProvider->supports($format)) {
             return;
         }
         $decoder = $this->decoderProvider->getDecoder($format);
         $data = $decoder->decode($request->getContent(), $format);
         if (is_array($data)) {
             $request->request = new ParameterBag($data);
         }
     }
 }
示例#6
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     //@todo
     if ($request->headers->has('x-wsse')) {
         $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
         if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
             $token = new LdapUserToken();
             $token->setUser($matches[1]);
             $token->setDigest($matches[2]);
             $token->setNonce($matches[3]);
             $token->setCreated($matches[4]);
             try {
                 $returnValue = $this->authenticationManager->authenticate($token);
                 if ($returnValue instanceof TokenInterface) {
                     $this->securityContext->setToken($returnValue);
                 } elseif ($returnValue instanceof Response) {
                     $event->setResponse($returnValue);
                 }
                 return null;
             } catch (AuthenticationException $e) {
                 // you might log something here
             }
         }
     }
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
示例#7
0
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $apiKey = $request->headers->get('Authorization', $request->query->get('api_key'));
     if (!$apiKey) {
         if (true === $this->forceApiKey) {
             $response = new Response();
             $response->setStatusCode(401);
             $event->setResponse($response);
         }
         return;
     }
     $token = new ApiKeyUserToken();
     $token->setApiKey($apiKey);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     if ($this->isJsonRequest($request)) {
         $response = new JsonResponse(array('error' => $message));
     } else {
         $response = new Response();
         $response->setContent($message);
     }
     $response->setStatusCode(401);
     $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->query->has($this->options['signed_login_parameter'])) {
         return;
     }
     try {
         $token = $this->createToken($request);
         $token = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($token);
     } catch (AuthenticationException $e) {
         $this->tokenStorage->setToken(null);
         if ($this->failureHandler instanceof AuthenticationFailureHandlerInterface) {
             $response = $this->failureHandler->onAuthenticationFailure($request, $e);
             if ($response instanceof Response) {
                 $event->setResponse($response);
             } elseif (null !== $response) {
                 throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null or a Response object', get_class($this->failureHandler)));
             }
         }
         return;
     }
     if ($this->successHandler instanceof AuthenticationSuccessHandlerInterface) {
         $response = $this->successHandler->onAuthenticationSuccess($request, $token);
         if ($response instanceof Response) {
             $event->setResponse($response);
         } elseif (null !== $response) {
             throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null or a Response object', get_class($this->successHandler)));
         }
     }
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseHeader = $request->headers->get(self::WSSE_HEADER, false);
     if (!$wsseHeader || 1 !== preg_match(self::WSSE_REGEX, $wsseHeader, $matches)) {
         $event->setResponse(new Response('', Response::HTTP_FORBIDDEN, array('WWW-Authenticate' => 'WSSE realm="webservice", profile="ApplicationToken"')));
         return;
     }
     $token = new TelenorUserToken($this->providerKey, $matches[2], $matches[3], $matches[4]);
     $token->setUser($matches[1]);
     try {
         $authenticatedToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authenticatedToken);
         return;
     } catch (NonceExpiredException $failed) {
         $this->logger->debug("Nonce expired: " . $wsseHeader);
     } catch (AuthenticationException $failed) {
         $this->logger->debug("Authentication failed: " . $failed->getMessage());
     }
     $token = $this->securityContext->getToken();
     if ($token instanceof TelenorUserToken) {
         $this->securityContext->setToken(null);
     }
     $response = new Response("", Response::HTTP_UNAUTHORIZED, array(Headers::LOCATION => $this->router->generate('telenor.authentication.login')));
     $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         return;
     }
     $user = $matches[1];
     $token = new WsseToken();
     $token->setUser($user);
     $token->setAttribute('digest', $matches[2]);
     $token->setAttribute('nonce', $matches[3]);
     $token->setAttribute('created', $matches[4]);
     try {
         $returnValue = $this->authenticationManager->authenticate($token);
         if ($returnValue instanceof TokenInterface) {
             if (!$returnValue->getUser()->isActive()) {
                 throw new AuthenticationException("Your account is not activated yet, please check your email and confirm registration.\n" . "If you didn't receive your verification email, please <a href=\"#reconfirm/{$user}\">click here.</a>");
             }
             return $this->securityContext->setToken($returnValue);
         } else {
             if ($returnValue instanceof Response) {
                 $event->setResponse($returnValue);
                 return;
             }
         }
     } catch (AuthenticationException $failed) {
         $this->logger->error(sprintf("Authentication failed for user %s. Reason: %s", $token->getUser(), $failed->getMessage()));
         $response = new Response($this->serializer->serialize(['message' => $failed->getMessage()], $request->getRequestFormat()), Codes::HTTP_UNAUTHORIZED);
         $event->setResponse($response);
     }
 }
示例#11
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '~UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([a-zA-Z0-9+/]+={0,2})", Created="([^"]+)"~';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         return;
     }
     $token = new WsseUserToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $response = new Response();
         $response->setStatusCode(Response::HTTP_FORBIDDEN);
         $response->setContent($failed->getMessage());
         $event->setResponse($response);
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(Response::HTTP_FORBIDDEN);
     $response->setContent("WSSE authentication failed");
     $event->setResponse($response);
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     // Only operate on the master request
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     if (!$request->hasSession()) {
         return;
     }
     $session = $request->getSession();
     $session->start();
     $session_data = $session->getMetadataBag();
     // Expire sessions if unused for $idletimeout
     $idle_timeout = $this->container->getParameter('tui_session.session_timeout');
     if (time() - $session_data->getLastUsed() > $idle_timeout) {
         $session->invalidate();
         // Return custom response if provided
         $expiry_response = $this->container->getParameter('tui_session.expired_response');
         if ($expiry_response) {
             $event->setResponse($this->container->get($expiry_response));
             return;
         }
         // Redirect to route name if provided
         $path = $this->container->getParameter('tui_session.redirect_to');
         if ($path) {
             $url = $this->container->get('router')->generate($path);
             $response = new RedirectResponse($url);
             $event->setResponse($response);
             return;
         }
         throw new CredentialsExpiredException();
     }
 }
示例#13
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $currentRoute = $request->attributes->get('_route');
     if (!$this->session->has('LDAP_LOGIN_CALLBACK')) {
         if (in_array($currentRoute, $this->allowedRoutes)) {
             $this->session->set('LDAP_LOGIN_CALLBACK', $this->kernel->getParameter('rheck_ldap_firewall.default_url'));
         } else {
             $this->session->set('LDAP_LOGIN_CALLBACK', $currentRoute);
         }
     }
     if (in_array($currentRoute, $this->allowedRoutes)) {
         return;
     }
     if (!$this->session->has('LDAP_LOGIN')) {
         $loginUrl = $this->router->generate($this->kernel->getParameter('rheck_ldap_firewall.login_url'));
         $event->setResponse(RedirectResponse::create($loginUrl));
         return;
     }
     $ldapUserCredentials = $this->session->get('LDAP_LOGIN');
     $token = new LDAPToken();
     $token->setUser('ldap_proxy_user');
     $token->setLDAPUserCredentials($ldapUserCredentials);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $this->session->set('LDAP_LOGIN_ERROR', 'Some error was occurred! Can\'t connect to LDAP.');
         $event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
     } catch (\Exception $e) {
         $this->session->set('LDAP_LOGIN_ERROR', 'Invalid credentials.');
         $event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
     }
 }
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($request->headers->has('x-wsse')) {
         $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
         if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
             $token = new WsseToken();
             $token->setUser($matches[1]);
             $token->digest = $matches[2];
             $token->nonce = $matches[3];
             $token->created = $matches[4];
             try {
                 $returnValue = $this->authenticationManager->authenticate($token);
                 if ($returnValue instanceof TokenInterface) {
                     return $this->securityContext->setToken($returnValue);
                 } else {
                     if ($returnValue instanceof Response) {
                         return $event->setResponse($returnValue);
                     }
                 }
             } catch (AuthenticationException $authException) {
                 $response = new Response();
                 $response->setStatusCode(401, $authException ? $authException->getMessage() : null);
                 $event->setResponse($response);
                 return;
             }
         }
     }
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
示例#16
0
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     /* @var $request Request */
     $request = $event->getRequest();
     $file = $request->getScriptName() == '/app_dev.php' ? $request->getPathInfo() : $request->getScriptName();
     if (is_file($file = $this->root_dir . '/../web' . $file)) {
         $response = (new Response())->setPublic();
         // caching in prod env
         if ($this->env == 'prod') {
             $response->setEtag(md5_file($file))->setExpires((new \DateTime())->setTimestamp(time() + 2592000))->setLastModified((new \DateTime())->setTimestamp(filemtime($file)))->headers->addCacheControlDirective('must-revalidate', true);
             // response was not modified for this request
             if ($response->isNotModified($request)) {
                 $event->setResponse($response);
                 return;
             }
         }
         // set content type
         $mimes = ['css' => 'text/css', 'js' => 'text/javascript'];
         if (isset($mimes[$ext = pathinfo($file, PATHINFO_EXTENSION)])) {
             $response->headers->set('Content-Type', $mimes[$ext]);
         } else {
             $response->headers->set('Content-Type', mime_content_type($file));
         }
         $event->setResponse($response->setContent(file_get_contents($file)));
     }
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     // skip if not a CORS request
     if (!$request->headers->has('Origin') || $request->headers->get('Origin') == $request->getSchemeAndHttpHost()) {
         return;
     }
     $options = $this->configurationResolver->getOptions($request);
     if (!$options) {
         return;
     }
     // perform preflight checks
     if ('OPTIONS' === $request->getMethod()) {
         $event->setResponse($this->getPreflightResponse($request, $options));
         return;
     }
     if (!$this->checkOrigin($request, $options)) {
         $response = new Response('', 403, array('Access-Control-Allow-Origin' => 'null'));
         $event->setResponse($response);
         return;
     }
     $this->dispatcher->addListener('kernel.response', array($this, 'onKernelResponse'));
     $this->options = $options;
 }
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 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->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     $response = new Response();
     $response->setContent($message);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
示例#19
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->headers->has('x-wsse')) {
         return;
     }
     $wsseHeader = trim($request->headers->get('x-wsse'));
     if (!strlen($wsseHeader)) {
         return;
     }
     $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (preg_match($wsseRegex, $wsseHeader, $matches)) {
         $token = new WsseUserToken();
         $token->setUser($matches[1]);
         $token->digest = $matches[2];
         $token->nonce = $matches[3];
         $token->created = $matches[4];
         try {
             $returnValue = $this->authenticationManager->authenticate($token);
             if ($returnValue instanceof TokenInterface) {
                 return $this->securityContext->setToken($returnValue);
             } else {
                 if ($returnValue instanceof Response) {
                     return $event->setResponse($returnValue);
                 }
             }
         } catch (\Exception $e) {
             //echo "exception caught " . $e->getMessage();
         }
     }
     $event->setResponse($this->entryPoint->start($request, new AuthenticationException("Foo")));
 }
 /**
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     // @todo make endpoint(s) customizable
     if ($event->getRequest()->getMethod() !== 'POST') {
         return;
     }
     if ($event->getRequest()->getPathInfo() != '/xmlrpc' && $event->getRequest()->getPathInfo() != '/xmlrpc.php') {
         return;
     }
     try {
         $request = $this->requestGenerator->generateFromRequest($event->getRequest());
         if (isset($this->logger)) {
             $this->logger->debug((string) $request);
         }
     } catch (UnexpectedValueException $e) {
         $event->setResponse(new Response("Invalid request XML\n" . $e->getMessage(), 400));
         return;
     }
     // @todo refactor to dynamically set follow-up events instead of testing (cors bundle like)
     $request->attributes->set('IsXmlRpcRequest', true);
     $requestContext = new RequestContext();
     $requestContext->fromRequest($request);
     $originalContext = $this->router->getContext();
     $this->router->setContext($requestContext);
     $response = $this->httpKernel->handle($request);
     $event->setResponse($response);
     $this->router->setContext($originalContext);
     if ($response instanceof Response) {
         $event->setResponse($response);
     }
 }
示例#21
0
 /**
  * {@inheritDoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($request->getMethod() === 'OPTIONS') {
         $this->securityContext->setToken(new AnonymousToken('', 'anon.', array()));
         return;
     }
     $regex = '/Bearer (.*)/';
     if (!$request->headers->has('Authorization') || preg_match($regex, $request->headers->get('Authorization'), $matches) !== 1) {
         $event->setResponse($this->getInvalidRequestResponse());
         return;
     }
     $token = new OAuth2UserToken();
     $token->setOAuthToken($matches[1]);
     $token->request = $request;
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $event->setResponse($this->getInvalidTokenReponse());
         return;
     }
     $event->setResponse($this->getInvalidTokenReponse());
 }
示例#22
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$this->app['phraseanet.configuration']['api_cors']['enabled']) {
         return;
     }
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     if (!preg_match('{api/v(\\d+)}i', $request->getPathInfo() ?: '/')) {
         return;
     }
     // skip if not a CORS request
     if (!$request->headers->has('Origin') || $request->headers->get('Origin') == $request->getSchemeAndHttpHost()) {
         return;
     }
     $options = array_merge(['allow_credentials' => false, 'allow_origin' => [], 'allow_headers' => [], 'allow_methods' => [], 'expose_headers' => [], 'max_age' => 0, 'hosts' => []], $this->app['phraseanet.configuration']['api_cors']);
     // skip if the host is not matching
     if (!$this->checkHost($request, $options)) {
         return;
     }
     // perform preflight checks
     if ('OPTIONS' === $request->getMethod()) {
         $event->setResponse($this->getPreflightResponse($request, $options));
         return;
     }
     if (!$this->checkOrigin($request, $options)) {
         $response = new Response('', 403, ['Access-Control-Allow-Origin' => 'null']);
         $event->setResponse($response);
         return;
     }
     $this->app['dispatcher']->addListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);
     $this->options = $options;
 }
示例#23
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         return;
     }
     $token = new WsseUserToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     // Check if authentication Token is present
     if ($request->headers->has('x-wsse')) {
         // Token parser
         $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
         if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
             $token = new WsseUserToken();
             $token->setUser($matches[1]);
             $token->digest = $matches[2];
             $token->nonce = $matches[3];
             $token->created = $matches[4];
             try {
                 // Authentication process
                 $authToken = $this->authenticationManager->authenticate($token);
                 $this->securityContext->setToken($authToken);
                 return;
             } catch (AuthenticationException $failed) {
                 // ... you might log something here
                 // To deny the authentication clear the token. This will redirect to the login page.
                 // $this->securityContext->setToken(null);
                 // return;
                 // Deny authentication with a '403 Forbidden' HTTP response
                 $response = new Response();
                 $response->setStatusCode(403);
                 $event->setResponse($response);
             }
         }
     }
     // By default deny authentication
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 /**
  * Determine whether the page is configured to be offline.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function onKernelRequestMaintenance(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $route_match = RouteMatch::createFromRequest($request);
     $path = $request->attributes->get('_system_path');
     if ($this->maintenanceMode->applies($route_match)) {
         // If the site is offline, log out unprivileged users.
         if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
             user_logout();
             // Redirect to homepage.
             $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
             return;
         }
         if ($this->account->isAnonymous() && $path == 'user') {
             // Forward anonymous user to login page.
             $event->setResponse(new RedirectResponse($this->url('user.login', [], ['absolute' => TRUE])));
             return;
         }
     }
     if ($this->account->isAuthenticated()) {
         if ($path == 'user/login') {
             // If user is logged in, redirect to 'user' instead of giving 403.
             $event->setResponse(new RedirectResponse($this->url('user.page', [], ['absolute' => TRUE])));
             return;
         }
         if ($path == 'user/register') {
             // Authenticated user should be redirected to user edit page.
             $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
             return;
         }
     }
 }
示例#26
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseHeader = $request->headers->get(self::WSSE_HEADER, false);
     if (!$wsseHeader || 1 !== preg_match(self::WSSE_REGEX, $wsseHeader, $matches)) {
         $event->setResponse(new Response('', Response::HTTP_FORBIDDEN, array('WWW-Authenticate' => 'WSSE realm="webservice", profile="ApplicationToken"')));
         return;
     }
     $token = new WsseUserToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (NonceExpiredException $failed) {
         $this->logger->debug("Nonce expired: " . $wsseHeader);
     } catch (AuthenticationException $failed) {
         $this->logger->debug("Authentication failed: " . $failed->getMessage());
     }
     $token = $this->securityContext->getToken();
     if ($token instanceof WsseUserToken) {
         $this->securityContext->setToken(null);
     }
     $response = new Response();
     $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
     $event->setResponse($response);
 }
示例#27
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     //On récupère la route courante
     $route = $event->getRequest()->attributes->get('_route');
     //On vérifie que la route correspond à la route livraison ou validation, Si oui :
     if ($route == 'ticme_front_cart_delivery' || $route == 'ticme_front_cart_validation') {
         //On vérifie que la variable de session panier éxiste
         if ($this->session->has('cart')) {
             //On compte le nombre d'éléments dans le panier, si il est égale à 0 on ne peut donc pas poursuivre la validation du panier
             //On redirige donc vers la route du panier qui affichera "Aucun articles dans votre panier"
             if (count($this->session->get('cart')) == 0) {
                 $event->setResponse(new RedirectResponse($this->router->generate('ticme_front_cart')));
             }
         }
         /* On vérifie que l'objet utilisateur existe en session (et donc identifié car s'il n'éxiste pas cela veut dire que le user n'est pas connecté)
          * sinon on le redirige vers le formulaire de connexion de FOS
          */
         if (!is_object($this->securityContext->getToken()->getUser())) {
             $this->session->getFlashBag()->add('notification', 'Vous devez vous identifier');
             /*
              * L'objet RedirectResponse qui étend l'objet Response que nous connaissons bien, en lui ajoutant l'entête HTTP Location
              * qu'il faut pour que notre navigateur comprenne qu'il s'agit d'une redirection.
              */
             $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
         }
     }
 }
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->securityContext->getToken()) {
         return;
     }
     $request = $event->getRequest();
     if (!$request->hasSession()) {
         throw new \RuntimeException('This authentication method requires a session.');
     }
     $cookies = array_intersect_key($request->cookies->all(), array_flip(array_filter(array_keys($request->cookies->all()), function ($input) {
         return strpos($input, 'wordpress_logged_in_') === 0;
     })));
     $logger = $this->logger;
     if (empty($cookies)) {
         return;
     }
     if (null !== $this->logger) {
         $this->logger->debug('Found eligible cookies prefixed with wordpress_logged_in_');
     }
     $script = call_user_func($this->script, InjectRequestGlobals::toSubprocessGlobals($request), "\$user = wp_get_current_user(); echo json_encode(\$user);");
     $process = new PhpProcess('<?php ' . $script, $this->documentRoot);
     $process->run();
     $output = $process->getOutput();
     $user = json_decode($output);
     // Attempt to load a WordPress user based on cookies for this site's domain.
     if (!$user || isset($user->ID) && $user->ID === 0) {
         return;
     }
     // Translate WordPress roles into Symfony Security component roles.
     $roles = array_map(function ($input) {
         return 'ROLE_WORDPRESS_' . strtoupper($input);
     }, $user->roles);
     $roles[] = 'ROLE_USER';
     // Generate token.
     $token = new WordpressUserToken($roles);
     $token->setUser($user->data->display_name);
     try {
         // Authorize token.
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         // To deny the authentication clear the token. This will redirect to the login page.
         // Make sure to only clear your token, not those of other authentication listeners.
         $token = $this->securityContext->getToken();
         if ($token instanceof WordpressUserToken) {
             $this->securityContext->setToken(null);
         }
         // Deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
示例#29
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     // Check if authentication Token is present
     if ($request->headers->has('x-wsse')) {
         // Token parser
         $wsseRegex = '/UsernameToken Username="******"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
         if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
             $token = new WsseUserToken();
             $token->setUser($matches[1]);
             $token->digest = $matches[2];
             $token->nonce = $matches[3];
             $token->created = $matches[4];
             try {
                 // Authentication process
                 $authToken = $this->authenticationManager->authenticate($token);
                 $this->securityContext->setToken($authToken);
                 return;
             } catch (AuthenticationException $failed) {
                 $failedMessage = 'WSSE Login failed for ' . $token->getUsername() . '. Why ? ' . $failed->getMessage();
                 $this->logger->err($failedMessage);
                 // To deny the authentication clear the token. This will redirect to the login page.
                 // $token = $this->securityContext->getToken();
                 // if ( $token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
                 //     $this->securityContext->setToken(null);
                 // }
                 // Deny authentication with a '403 Forbidden' HTTP response
                 $response = new Response();
                 $response->setStatusCode(403);
                 $response->setContent($failedMessage);
                 $event->setResponse($response);
                 return;
             } catch (NonceExpiredException $expired) {
                 $failedMessage = 'WSSE Nonce Expired for ' . $token->getUsername() . '. Why ? ' . $failed->getMessage();
                 $this->logger->err($failedMessage);
                 // Deny authentication with a '403 Forbidden' HTTP response
                 $response = new Response();
                 $response->setStatusCode(403);
                 $response->setContent($failedMessage);
                 $event->setResponse($response);
                 return;
             }
             // By default deny authorization
             $response = new Response();
             $response->setStatusCode(403);
             $event->setResponse($response);
         }
     }
     // By default deny authentication
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
示例#30
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $session = $request->getSession();
     if ($request->getClientIp() == '127.0.0.1') {
         $session->set('open_id', 'o5mOVuGapiB3tzYysVcE4xstN3s4');
         $session->set('user_id', 1);
     } else {
         if ($session->get('open_id') === null && $request->attributes->get('_route') !== '_callback' && stripos($request->attributes->get('_controller'), 'DefaultController') !== false) {
             $app_id = $this->container->getParameter('wechat_appid');
             $session->set('redirect_url', $request->getUri());
             $state = '';
             $callback_url = $request->getUriForPath('/callback');
             //$callback_url = $this->router->generate('_callback','');
             $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $app_id . "&redirect_uri=" . $callback_url . "&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
             $event->setResponse(new RedirectResponse($url));
         }
         $appId = $this->container->getParameter('wechat_appid');
         $appSecret = $this->container->getParameter('wechat_secret');
         $wechat = new Wechat\Wechat($appId, $appSecret);
         $wx = (object) $wechat->getSignPackage();
         $session->set('wx_app_id', $wx->appId);
         $session->set('wx_timestamp', $wx->timestamp);
         $session->set('wx_nonce_str', $wx->nonceStr);
         $session->set('wx_signature', $wx->signature);
     }
     if (stripos($request->attributes->get('_controller'), 'DefaultController') !== false) {
         if (null == $request->get('store_id')) {
             $store_id = null == $session->get('store_id') ? 1 : $session->get('store_id');
         } else {
             $store_id = $request->get('store_id');
         }
         $session->set('store_id', $store_id);
         $store = $this->em->getRepository('AppBundle:Store')->find($session->get('store_id'));
         if ($store !== null) {
             $session->set('storeImg', $store->getPageHeaderImg());
             $session->set('storeDescription', $store->getDescription());
             $session->set('pageTitle', $store->getTitle());
             $session->set('storeInfo', $store->getInfo());
             $session->set('storeName', $store->getStoreName());
             $session->set('storeAddress', $store->getAddress());
             $session->set('storeTel', $store->getTel());
             $session->set('wechat_title', $store->getWxTitle());
             $session->set('wechat_desc', $store->getWxDesc());
             $session->set('wechat_img_url', $store->getWxImg());
             $session->set('wx_share_url', 'http://' . $request->getHost() . $this->router->generate('_index', array('store_id' => $store->getId())));
         }
         #店铺关闭状态
         if ((null == $store || $store->getIsActive() == 0) && $request->attributes->get('_route') != '_close') {
             $event->setResponse(new RedirectResponse($this->router->generate('_close')));
         }
     }
 }