public function setRequestLayout(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     // Get the necessary informations to check them in layout configurations
     $path = $request->getPathInfo();
     $host = $request->getHost();
     $layouts = $this->config['layouts'];
     // As a layout must be set, we force it to be empty if no layout is properly configured.
     // Then this will throw an exception, and the user will be warned of the "no-layout" config problem.
     $finalLayout = null;
     foreach ($layouts as $layoutConfig) {
         $match = false;
         if ($layoutConfig['host'] && $host === $layoutConfig['host']) {
             $match = true;
         }
         if ($layoutConfig['pattern'] && preg_match('~' . $layoutConfig['pattern'] . '~', $path)) {
             $match = true;
         }
         if ($match) {
             $finalLayout = $layoutConfig;
             break;
         }
     }
     if (null === $finalLayout || !$this->templating->exists($finalLayout['resource'])) {
         throw new \Twig_Error_Loader(sprintf('Unable to find template %s for layout %s. The "layout" parameter must be a valid twig view to be used as a layout.', $finalLayout['resource'], $finalLayout['name']), 0, $finalLayout['resource']);
     }
     $event->getRequest()->attributes->set('_orbitale_cms_layout', $finalLayout);
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     // Check master request
     if (!$event->isMasterRequest()) {
         return;
     }
     // Check excluded paths
     $path = $event->getRequest()->getPathInfo();
     if ($this->isExcludedPath($path)) {
         return;
     }
     // Extract token
     $headerToken = $this->tokenExtractor->extract($event->getRequest());
     if (!is_string($headerToken)) {
         throw new AuthenticationExpiredException('The access token is missing');
     }
     $token = $this->tokenVerificator->parsing($headerToken);
     // Validate token
     if (!$this->tokenVerificator->isValid($token)) {
         throw new AuthenticationExpiredException('The access token is invalid');
     }
     // Store token
     $this->tokenStorage->setToken($token);
     // token
     $operator = $token->getClaim('operatorId');
     $event->getRequest()->request->set('operator', $operator);
     $event->getRequest()->query->set('operator', $operator);
 }
 private function handleEvent(GetResponseEvent $event)
 {
     /** @var SessionHandler $sessionHandler */
     $sessionHandler = $this->container->get('ra.security.authentication.session_handler');
     // reinstate the token from the session. Could be expanded with logout check if needed
     if ($this->getTokenStorage()->getToken()) {
         return;
     }
     /** @var SamlInteractionProvider $samlInteractionProvider */
     $samlInteractionProvider = $this->container->get('ra.security.authentication.saml');
     if (!$samlInteractionProvider->isSamlAuthenticationInitiated()) {
         $sessionHandler->setCurrentRequestUri($event->getRequest()->getUri());
         $event->setResponse($samlInteractionProvider->initiateSamlRequest());
         /** @var SamlAuthenticationLogger $logger */
         $logger = $this->container->get('surfnet_saml.logger')->forAuthentication($sessionHandler->getRequestId());
         $logger->notice('Sending AuthnRequest');
         return;
     }
     /** @var SamlAuthenticationLogger $logger */
     $logger = $this->container->get('surfnet_saml.logger')->forAuthentication($sessionHandler->getRequestId());
     $expectedInResponseTo = $sessionHandler->getRequestId();
     try {
         $assertion = $samlInteractionProvider->processSamlResponse($event->getRequest());
     } catch (PreconditionNotMetException $e) {
         $logger->notice(sprintf('SAML response precondition not met: "%s"', $e->getMessage()));
         $event->setResponse($this->renderPreconditionExceptionResponse($e));
         return;
     } catch (Exception $e) {
         $logger->error(sprintf('Failed SAMLResponse Parsing: "%s"', $e->getMessage()));
         throw new AuthenticationException('Failed SAMLResponse parsing', 0, $e);
     }
     if (!InResponseTo::assertEquals($assertion, $expectedInResponseTo)) {
         $logger->error('Unknown or unexpected InResponseTo in SAMLResponse');
         throw new AuthenticationException('Unknown or unexpected InResponseTo in SAMLResponse');
     }
     $logger->notice('Successfully processed SAMLResponse, attempting to authenticate');
     $loaResolutionService = $this->container->get('surfnet_stepup.service.loa_resolution');
     $loa = $loaResolutionService->getLoa($assertion->getAuthnContextClassRef());
     $token = new SamlToken($loa);
     $token->assertion = $assertion;
     /** @var AuthenticationProviderManager $authenticationManager */
     $authenticationManager = $this->container->get('security.authentication.manager');
     try {
         $authToken = $authenticationManager->authenticate($token);
     } catch (BadCredentialsException $exception) {
         $logger->error(sprintf('Bad credentials, reason: "%s"', $exception->getMessage()), ['exception' => $exception]);
         $event->setResponse($this->renderBadCredentialsResponse($exception));
         return;
     } catch (AuthenticationException $failed) {
         $logger->error(sprintf('Authentication Failed, reason: "%s"', $failed->getMessage()), ['exception' => $failed]);
         $event->setResponse($this->renderAuthenticationExceptionResponse($failed));
         return;
     }
     // for the current request
     $this->getTokenStorage()->setToken($authToken);
     // migrate the session to prevent session hijacking
     $sessionHandler->migrate();
     $event->setResponse(new RedirectResponse($sessionHandler->getCurrentRequestUri()));
     $logger->notice('Authentication succeeded, redirecting to original location');
 }
Beispiel #4
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);
         }
     }
 }
Beispiel #5
0
 /**
  * Resolve issue on request
  *
  * @param GetResponseEvent $event GetResponseEvent event
  *
  * @return void
  */
 public function onRequest(GetResponseEvent $event)
 {
     $onAdminInterface = strpos($event->getRequest()->getRequestUri(), '/admin');
     if ($onAdminInterface === false && $event->getRequest()->get('_route') != 'newscoop_get_img') {
         $this->issueService->issueResolver($event->getRequest());
     }
 }
 /**
  * Checks if after a reload if the locale has changed.
  * If the user is logged in, the route is the default application route and the locale has changed,
  * the user locale will be modified
  *
  * @param GetResponseEvent $event
  */
 public function switchLocaleOnRequest(GetResponseEvent $event)
 {
     // no user is set in the access token
     // which means that no system user is authenticated and
     // that trigger is irrelevant
     if (null === ($user = $this->userFetcher->resolve())) {
         return;
     }
     $userLocale = $user->getSimpleProfile()->getLocale();
     if ($userLocale === ($cookie = $event->getRequest()->cookies->get('locale'))) {
         return;
     }
     $validLocale = true;
     try {
         $user->changeUserLocale($cookie);
     } catch (ChangeUserLocaleException $ex) {
         $validLocale = false;
         $request = $event->getRequest();
         $request->cookies->remove('locale');
         $request->setLocale($userLocale);
         $request->attributes->set('_locale', $userLocale);
     }
     // if the locale is invalid,
     // the cookie will be fixed in the response event
     if (!$validLocale) {
         $this->fixCookie = true;
         return;
     }
     $this->userRepository->modify($user);
 }
Beispiel #7
0
 /**
  * If users flag isFirstLogin is true redirect to change password page.
  *
  * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     // Don't do anything if it's not the master request or another firewall than "secured"
     $isSecuredArea = (bool) preg_match('/^\\/secured/', $event->getRequest()->getPathInfo());
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType() || !$isSecuredArea) {
         return;
     }
     $token = $this->tokenStorage->getToken();
     // Bypass listener if token does not match UsernamePasswordToken
     if (!$token instanceof UsernamePasswordToken) {
         return;
     }
     $changePasswordUrl = $this->router->generate('OpitOpitHrmUserBundle_user_change_password', array(), true);
     $excludedRoutes = array($this->router->generate('OpitOpitHrmUserBundle_logout', array(), true), $changePasswordUrl);
     if (null !== $token && is_object($token->getUser())) {
         // Bypass the change password page if user has ldap auth enabled
         if ($token->getUser()->isLdapEnabled()) {
             return;
         }
         if (in_array($event->getRequest()->getUri(), $excludedRoutes)) {
             return;
         }
         if ($token->getUser()->getIsFirstLogin()) {
             $event->setResponse(new RedirectResponse($changePasswordUrl));
         }
     }
 }
Beispiel #8
0
 public function testAnalyze()
 {
     $this->getResponseEvent->isMasterRequest()->willReturn(true);
     $this->getResponseEvent->getRequest()->willReturn(new Request());
     $this->requestListener->onKernelRequest($this->getResponseEvent->reveal());
     $this->requestAnalyzer->analyze(Argument::any())->shouldHaveBeenCalled();
 }
 public function handle(GetResponseEvent $event)
 {
     if (!$this->cas->isValidationRequest($event->getRequest())) {
         return;
     }
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Checking secure context token: %s', $this->securityContext->getToken()));
     }
     list($username, $attributes) = $this->getTokenData($event->getRequest());
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token instanceof CasAuthenticationToken && $token->isAuthenticated() && (string) $token === $username) {
             return;
         }
     }
     try {
         $token = $this->authenticationManager->authenticate(new CasAuthenticationToken($username, $attributes));
         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()));
         }
     }
 }
Beispiel #10
0
 public function checkToto(GetResponseEvent $event)
 {
     $tot = $event->getRequest()->query->get('toto');
     if (!is_null($tot)) {
         $event->getRequest()->query->set('tata', $tot);
     }
 }
 /**
  * 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 onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         return;
     }
     if ($event->getRequest()->get("_route") == $this->changePasswordRoute || substr($event->getRequest()->get("_route"), 0, 8) == "_assetic") {
         return;
     }
     $token = $this->security->getToken();
     if (!$token) {
         return;
     }
     $user = $token->getUser();
     if (!$user) {
         return;
     }
     $lastUserPassword = $this->em->getRepository("ACSEOChangePasswordBundle:PasswordHistory")->findOneBy(array("user" => $user), array("createdAt" => "DESC"), 1);
     if (!$lastUserPassword) {
         return;
     }
     $lastPasswordDate = $lastUserPassword->getCreatedAt();
     if ($lastPasswordDate->add(new \DateInterval($this->passwordExpireAfter)) < new \Datetime()) {
         if ($this->enableFlashbagMessage) {
             $event->getRequest()->getSession()->getFlashBag()->add("danger", "Votre mot de passe a expiré, vous devez en saisir un nouveau");
         }
         $response = new RedirectResponse($this->router->generate($this->changePasswordRoute));
         $event->setResponse($response);
     }
 }
Beispiel #13
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->hasPreviousSession()) {
         return;
     }
     $attributes = $event->getRequest()->attributes;
     //if have any route param return null
     if (!$attributes->has('_route_params')) {
         return;
     }
     //for all route params
     foreach ($attributes->get('_route_params') as $paramKey => $param) {
         // if there is a param which matches with id key
         if (preg_match('/id/', $paramKey)) {
             /**
              * throw not found exception because pg type db max value is 2147483647
              * @look {https://www.postgresql.org/docs/9.1/static/datatype-numeric.html}
              */
             if ((int) $param && (int) $param > 2147483647) {
                 //throw new NotFoundHttpException;
             }
         }
     }
 }
 /**
  * @param GetResponseEvent $event
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  * @return bool
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (strpos($event->getRequest()->attributes->get('_controller'), 'Api\\Resource') !== false) {
         header('Access-Control-Allow-Origin: *');
         $controller = explode('::', $event->getRequest()->attributes->get('_controller'));
         $reflection = new \ReflectionMethod($controller[0], $controller[1]);
         $scopeAnnotation = $this->reader->getMethodAnnotation($reflection, 'Etu\\Core\\ApiBundle\\Framework\\Annotation\\Scope');
         if ($scopeAnnotation) {
             $requiredScope = $scopeAnnotation->value;
         } else {
             $requiredScope = null;
         }
         if (!$requiredScope) {
             $requiredScope = 'public';
         }
         $request = $event->getRequest();
         $token = $request->query->get('access_token');
         $access = $this->server->checkAccess($token, $requiredScope);
         if (!$access->isGranted()) {
             $event->setResponse($this->formatter->format($event->getRequest(), ['error' => $access->getError(), 'error_message' => $access->getErrorMessage()], 403));
         } else {
             $event->getRequest()->attributes->set('_oauth_token', $access->getToken());
         }
     }
 }
 /**
  * Setup the route parameters.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *
  * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     LoggerRegistry::debug('EngineRouterListener performing start() on REQUEST event');
     $this->setRoutingAttributes($event->getRequest());
     $this->setTemplateAttributes($event->getRequest());
     LoggerRegistry::debug('EngineRouterListener will proceed with standard rendering');
 }
 /**
  * This method is executed for every Http Request.
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $route = $event->getRequest()->attributes->get('_route');
     // this intercepts the click
     if (isset($this->routesNames[$route])) {
         $routeDef = $this->routes[$this->routesNames[$route]];
         $em = $this->container->get('doctrine')->getEntityManager();
         $entityType = $routeDef['entity_type'];
         $entityName = $routeDef['entity_name'];
         if ($entityName != null) {
             $entityName = $request->attributes->get($entityName);
         }
         $entityId = $routeDef['entity_id'];
         if ($entityId != null) {
             if ($entityId != intval($entityId)) {
                 $entityId = $request->attributes->get($entityId);
             }
         }
         $click = $em->getRepository('JaitecClickBundle:Click')->findOneBy(array('entity_type' => $entityType, 'entity_id' => $entityId, 'entity_name' => $entityName));
         if (!$click) {
             $click = new Click();
             $click->setEntityType($entityType);
             $click->setEntityId($entityId);
             $click->setEntityName($entityName);
             $click->setClicks(1);
         } else {
             $click->setClicks(1 + $click->getClicks());
         }
         $em->persist($click);
         $em->flush();
     }
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     $this->logger->debug('Entity builder listener: catch kernel.request event');
     // If this is not a master request, skip handling
     if (!$event->isMasterRequest()) {
         $this->logger->debug('Entity builder listener: this is not master request, skip');
         return;
     }
     // If content already prepared
     if ($event->hasResponse()) {
         $this->logger->debug('Entity builder listener: event already has response, skip');
         return;
     }
     // Getting request
     $request = $event->getRequest();
     // Getting action
     $apiServerAction = $event->getRequest()->attributes->get('apiAction');
     /* @var $apiServerAction ApiServerAction */
     // Something wrong
     if (!$apiServerAction) {
         $this->logger->error('Request parser listener: request has no apiAction attribute, throwing access denied exception');
         throw new AccessDeniedHttpException();
     }
     // Creating request data entity
     try {
         $apiEntity = $apiServerAction->getRequestedEntity($request->attributes->get('apiData'));
     } catch (\Exception $e) {
         $this->logger->notice(sprintf('Request parser listener: unable to convert apiData to entity ("%s"), apiEntity set tu null', $e->getMessage()));
         $apiEntity = null;
     }
     // Setting request attributes
     $request->attributes->set('requestData', $apiEntity);
     // Cleaning request attributes
     $request->attributes->remove('apiData');
 }
Beispiel #18
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->isMasterRequest()) {
         $this->serverData = $event->getRequest()->server->all();
         $this->serverData['REMOTE_ADDR'] = $event->getRequest()->getClientIp();
     }
 }
 /**
  * @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);
     }
 }
 /**
  * Triggered on every request.
  *
  * See if the time since last active is larger than the maximum idle time that is allowed
  *
  * @param GetResponseEvent $event
  *
  * @return void
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     // only need to evalute the original request from the browser
     if (!$event->isMasterRequest()) {
         return;
     }
     // do nothing if user is not logged in
     if ($this->securityContext->getToken() !== null && !$this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
         return;
     }
     // do nothing if the post contains a systemKey and systemSecret
     if ($event->getRequest()->request->has('systemKey') && $event->getRequest()->request->has('systemSecret')) {
         return;
     }
     // assume an infinite session time is allowed if the parameter is <= 0 or not set, by doing nothing
     if ($this->maxIdleTime <= 0 || $this->maxIdleTime === null) {
         return;
     }
     // just incase a session hasn't started, otherwise it simply returns true
     $this->session->start();
     // have we been inactive for longer than the allowed time limit..?
     $timeSinceActive = time() - $this->session->getMetadataBag()->getLastUsed();
     if ($timeSinceActive > $this->maxIdleTime) {
         // log the user out
         $this->securityContext->setToken(null);
         // issue a message for the login page
         $this->session->getFlashBag()->set('session_timeout', 'Your session has expired due to inactivity.');
         // redirect to login
         $event->setResponse(new RedirectResponse($this->router->generate('barbon_hostedapi_app_index_index')));
     }
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onCoreRequest(GetResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         return;
     }
     $token = $this->securityContext->getToken();
     if (!$token) {
         return;
     }
     if (!$token instanceof UsernamePasswordToken) {
         return;
     }
     $key = $this->helper->getSessionKey($this->securityContext->getToken());
     $request = $event->getRequest();
     $session = $event->getRequest()->getSession();
     $user = $this->securityContext->getToken()->getUser();
     if (!$session->has($key)) {
         return;
     }
     if ($session->get($key) === true) {
         return;
     }
     $state = 'init';
     if ($request->getMethod() == 'POST') {
         if ($this->helper->checkCode($user, $request->get('_code')) == true) {
             $session->set($key, true);
             return;
         }
         $state = 'error';
     }
     $event->setResponse($this->templating->renderResponse('SonataUserBundle:Admin:Security/two_step_form.html.twig', array('state' => $state)));
 }
Beispiel #22
0
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->hasPreviousSession()) {
         return;
     }
     $localeFromSession = $request->getSession()->get('_locale');
     $localeFromRoute = $request->query->get('_locale');
     $localeFromHeader = $request->getPreferredLanguage($this->availableLocales);
     // при переключении языка в веб-интерфейсе (язык в роуте)
     if ($localeFromRoute) {
         $request->getSession()->set('_locale', $localeFromRoute);
         $request->setLocale($localeFromSession);
         $route = $event->getRequest()->get('_route');
         $params = $request->attributes->get('_route_params');
         $url = $this->router->generate($route, $params);
         $response = new RedirectResponse($url);
         $event->setResponse($response);
         // при отсутствии языка в роуте
     } else {
         // берем локаль из сессии (дефолтное состояние при выбранной локали)
         if ($localeFromSession) {
             $request->setLocale($localeFromSession);
         } else {
             if ($localeFromHeader) {
                 $request->setLocale($localeFromHeader);
                 $request->getSession()->set('_locale', $localeFromHeader);
             }
         }
     }
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     // Request object
     $seesion = $request->getSession();
     $container = $this->container;
     switch ($request->query->get('lang')) {
         case "en":
             $seesion->set('_locale', 'en_US');
             $request->setLocale('en_US');
             break;
         case "fr":
             $seesion->set('_locale', 'fr_FR');
             $request->setLocale('fr_FR');
             break;
         default:
             if ($seesion->get('_locale') == "en_US") {
                 $seesion->set('_locale', 'en_US');
                 $request->setLocale('en_US');
             } else {
                 $seesion->set('_locale', 'fr_FR');
                 $request->setLocale('fr_FR');
             }
             //$response->headers->setCookie(new Cookie('test', 1));
             break;
     }
     $route = $event->getRequest()->get('_route');
     //formation_show
     //$controller = $event->getController();
     //exit(\Doctrine\Common\Util\Debug::dump($controller));
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->attributes->get('is_rest_request')) {
         return;
     }
     if (($contentTypeHeaderValue = $request->headers->get('content-type')) === null) {
         return;
     }
     list($mediaType) = explode('+', $contentTypeHeaderValue);
     if (strtolower($mediaType) == !'application/vnd.ez.api.contentcreate') {
         return;
     }
     $message = $this->buildMessage($request);
     if (!$message->body) {
         return;
     }
     $result = $this->restInputDispatcher->parse($message);
     if (!$result instanceof RestContentCreateStruct) {
         return;
     }
     // Not a user
     if (($userCreateData = $this->mapContentCreateToUserCreate($result)) === false) {
         return;
     }
     list($userCreateStruct, $userGroup) = $userCreateData;
     $createdUser = $this->repository->getUserService()->createUser($userCreateStruct, [$userGroup]);
     $createdContentInfo = $createdUser->contentInfo;
     $createdLocation = $this->repository->getLocationService()->loadLocation($createdContentInfo->mainLocationId);
     $contentType = $this->repository->getContentTypeService()->loadContentType($createdContentInfo->contentTypeId);
     $result = new CreatedContent(array('content' => new RestContent($createdContentInfo, $createdLocation, $this->repository->getContentService()->loadContent($createdContentInfo->id), $contentType, $this->repository->getContentService()->loadRelations($createdUser->getVersionInfo()))));
     $event->setResponse($this->viewDispatcher->dispatch($event->getRequest(), $result));
 }
 /**
  * If the request is a REST one, sets the is_rest_request request attribute.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $isRestRequest = true;
     if (!$this->hasRestPrefix($event->getRequest())) {
         $isRestRequest = false;
     }
     $event->getRequest()->attributes->set('is_rest_request', $isRestRequest);
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $event->getRequest()->setFormat('csv', 'text/csv');
     $event->getRequest()->setFormat('ods', 'application/vnd.oasis.opendocument.spreadsheet');
     $event->getRequest()->setFormat('pdf', ' application/pdf');
     $event->getRequest()->setFormat('xls', 'application/vnd.ms-excel');
     $event->getRequest()->setFormat('xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->isMasterRequest() && $event->getRequest()->attributes->has('page_id')) {
         // Notify listeners (eg. RoutePageListener) about Page associated to requested route
         $this->eventDispatcher->dispatch('swp.context.page', new GenericEvent(null, ['pageId' => $event->getRequest()->attributes->get('page_id'), 'route_name' => $event->getRequest()->attributes->get('_route')]));
     }
     return;
 }
Beispiel #28
0
 public function onRequest(GetResponseEvent $event)
 {
     $pos = strpos($_SERVER['REQUEST_URI'], '_profiler');
     if ($pos === false) {
         $request = $event->getRequest();
         $this->publicationService->poblicationResolver($event->getRequest());
     }
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     $priorities = array('text/html', 'application/json', '*/*');
     $format = $this->app['format.negociator']->getBest($event->getRequest()->headers->get('accept', '*/*'), $priorities);
     if (null === $format) {
         $this->app->abort(406, 'Not acceptable');
     }
     $event->getRequest()->setRequestFormat($event->getRequest()->getFormat($format->getValue()));
 }
Beispiel #30
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $this->request = $event->getRequest();
     $this->session = $event->getRequest()->getSession();
     if ($event->isMasterRequest()) {
         $this->journalService->setSelectedJournal();
         $this->loadClientUsers();
     }
 }