Call setResponse() to set the response that will be returned for the current request. The propagation of this event is stopped as soon as a response is set.
Inheritance: extends KernelEvent
 public function onKernelRequest(GetResponseEvent $event)
 {
     //GOAL:
     // Redirect all incoming requests to their /locale/route equivlent as long as the route will exists when we do so.
     // Do nothing if it already has /locale/ in the route to prevent redirect loops
     $request = $event->getRequest();
     $path = $request->getPathInfo();
     $route_exists = false;
     //by default assume route does not exist.
     foreach ($this->routeCollection as $routeObject) {
         $routePath = $routeObject->getPath();
         if ($routePath == "/{_locale}" . $path) {
             $route_exists = true;
             break;
         }
     }
     //If the route does indeed exist then lets redirect there.
     if ($route_exists == true) {
         //Get the locale from the users browser.
         $locale = $request->getPreferredLanguage();
         //If no locale from browser or locale not in list of known locales supported then set to defaultLocale set in config.yml
         if ($locale == "" || $this->isLocaleSupported($locale) == false) {
             $locale = $request->getDefaultLocale();
         }
         $event->setResponse(new RedirectResponse("/" . $locale . $path));
     }
     //Otherwise do nothing and continue on~
 }
示例#2
0
 public function handle(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     // there may not be authentication information on this request
     if (!$request->headers->has('Authorization')) {
         return;
     }
     return;
     // format should be "Authorization: token ABCDEFG"
     $tokenString = 'HARDCODED';
     if (!$tokenString) {
         // there's no authentication info for us to process
         return;
     }
     // create an object that just exists to hold onto the token string for us
     $token = new ApiAuthToken();
     $token->setAuthToken($tokenString);
     $returnValue = $this->authenticationManager->authenticate($token);
     if ($returnValue instanceof TokenInterface) {
         return $this->securityContext->setToken($returnValue);
     }
 }
示例#3
0
 /**
  * Sets the AJAX parameter from the current request.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The response event, which contains the current request.
  */
 public function onRequest(GetResponseEvent $event)
 {
     // Pass to the Html class that the current request is an Ajax request.
     if ($event->getRequest()->request->get(static::AJAX_REQUEST_PARAMETER)) {
         Html::setIsAjax(TRUE);
     }
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
         try {
             $controller = $event->getRequest()->attributes->get('_controller');
             if (strstr($controller, '::')) {
                 //Check if its a "real controller" not assetic for example
                 $generatorYaml = $this->getGeneratorYml($controller);
                 $generator = $this->getGenerator($generatorYaml);
                 $generator->setGeneratorYml($generatorYaml);
                 $generator->setBaseGeneratorName($this->getBaseGeneratorName($controller));
                 $generator->build();
             }
         } catch (NotAdminGeneratedException $e) {
             //Lets the word running this is not an admin generated module
         }
     }
     if ($this->container->hasParameter('admingenerator.twig')) {
         $twig_params = $this->container->getParameter('admingenerator.twig');
         if (isset($twig_params['date_format'])) {
             $this->container->get('twig')->getExtension('core')->setDateFormat($twig_params['date_format'], '%d days');
         }
         if (isset($twig_params['number_format'])) {
             $this->container->get('twig')->getExtension('core')->setNumberFormat($twig_params['number_format']['decimal'], $twig_params['number_format']['decimal_point'], $twig_params['number_format']['thousand_separator']);
         }
     }
 }
 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');
 }
 /**
  * Start collecting at the beginning of a request
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType() || !$this->driver || !$this->repository->isEnabled()) {
         return;
     }
     $this->driver->start();
 }
 /**
  * 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;
             }
         }
     }
 }
示例#8
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $request->setDefaultLocale($this->defaultLocale);
     $this->setLocale($request);
     $this->setRouterContext($request);
 }
示例#9
0
 /**
  * Add JSON handler to Whoops if Ajax request
  *
  * @param GetResponseEvent $event
  */
 public function onRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest() || !$event->getRequest()->isXmlHttpRequest()) {
         return;
     }
     $this->whoops->pushHandler(new JsonResponseHandler());
 }
示例#10
0
 /**
  * Get data from request and create Pagination and PartialResponse events.
  * @param  GetResponseEvent $event Event object with request
  */
 public function onRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     $pagination = new Pagination();
     $partialResponse = new PartialResponse();
     if ($request->query->has('page')) {
         $pagination->setPage($request->query->get('page'));
     }
     if ($request->query->has('sort')) {
         $pagination->setSort($request->query->get('sort'));
     }
     if ($request->query->has('items_per_page')) {
         $pagination->setItemsPerPage($request->query->get('items_per_page'));
     }
     if ($request->query->has('fields')) {
         $partialResponse->setFields($request->query->get('fields'));
     }
     $this->paginatorService->setPagination($pagination);
     $this->paginatorService->setPartialResponse($partialResponse);
     /**
      * Append all used parameters from get and post
      */
     $this->paginatorService->setUsedRouteParams(array_merge($request->query->all(), $request->request->all()));
 }
示例#11
0
 /**
  * Handles remember-me cookie based authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->securityContext->getToken()) {
         return;
     }
     $request = $event->getRequest();
     if (null === ($token = $this->rememberMeServices->autoLogin($request))) {
         return;
     }
     try {
         $token = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($token);
         if (null !== $this->dispatcher) {
             $loginEvent = new InteractiveLoginEvent($request, $token);
             $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
         }
         if (null !== $this->logger) {
             $this->logger->debug('SecurityContext populated with remember-me token.');
         }
     } catch (AuthenticationException $failed) {
         if (null !== $this->logger) {
             $this->logger->warn('SecurityContext not populated with remember-me token as the' . ' AuthenticationManager rejected the AuthenticationToken returned' . ' by the RememberMeServices: ' . $failed->getMessage());
         }
         $this->rememberMeServices->loginFail($request);
     }
 }
 /**
  * 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);
 }
示例#13
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST && $request->getMethod() == 'POST') {
         if (stripos($request->getPathInfo(), '/mapi') === 0) {
             return;
         }
         if (stripos($request->getPathInfo(), '/hls') === 0) {
             return;
         }
         $whiteList = array('/coin/pay/return/alipay', '/coin/pay/notify/alipay', '/coin/pay/notify/wxpay', '/pay/center/pay/alipay/return', '/pay/center/pay/wxpay/notify', '/pay/center/pay/alipay/notify', '/live/verify', '/course/order/pay/alipay/notify', '/vip/pay_notify/alipay', '/uploadfile/upload', '/uploadfile/cloud_convertcallback', '/uploadfile/cloud_convertcallback2', '/uploadfile/cloud_convertcallback3', '/uploadfile/cloud_convertheadleadercallback', '/disk/upload', '/file/upload', '/editor/upload', '/disk/convert/callback', '/partner/phpwind/api/notify', '/partner/discuz/api/notify', '/live/auth', '/edu_cloud/sms_callback');
         if (in_array($request->getPathInfo(), $whiteList)) {
             return;
         }
         if ($request->isXmlHttpRequest()) {
             $token = $request->headers->get('X-CSRF-Token');
         } else {
             $token = $request->request->get('_csrf_token', '');
         }
         $request->request->remove('_csrf_token');
         $expectedToken = $this->container->get('form.csrf_provider')->generateCsrfToken('site');
         if ($token != $expectedToken) {
             // @todo 需要区分ajax的response
             if ($request->getPathInfo() == '/admin') {
                 $token = $request->request->get('token');
                 $result = ServiceKernel::instance()->createService('CloudPlatform.AppService')->repairProblem($token);
                 $this->container->set('Topxia.RepairProblem', $result);
             } else {
                 $response = $this->container->get('templating')->renderResponse('TopxiaWebBundle:Default:message.html.twig', array('type' => 'error', 'message' => '页面已过期,请重新提交数据!', 'goto' => '', 'duration' => 0));
                 $event->setResponse($response);
             }
         }
     }
 }
 /**
  * onKernelRequest
  * 
  * @access public
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $siteManager = $this->getSiteManager();
     $domain = $event->getRequest()->server->get('SERVER_NAME');
     if (!$siteManager->getCurrentSite()) {
         $site = $siteManager->findSiteByDomain($domain);
         if ($site) {
             $siteManager->setCurrentSite($site);
         } else {
             if ($this->getConfigurationManager()->has('core.default_admin_site')) {
                 $defaultSite = $this->getConfigurationManager()->get('core.default_admin_site');
                 if ($defaultSite) {
                     $site = $siteManager->findSiteById($defaultSite);
                     if ($site) {
                         $siteManager->setCurrentSite($site);
                         return $site;
                     }
                 }
             }
         }
     }
     if ($this->getSecurityContext()->isGranted('ROLE_ADMIN')) {
         if (!$siteManager->getCurrentAdminSite() && $siteManager->getCurrentSite()) {
             $siteManager->setCurrentAdminSite($siteManager->getCurrentSite());
         }
     }
 }
示例#15
0
 /**
  * Set default timezone/locale
  *
  * @param GetResponseEvent $event
  *
  * @return void
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     // Set the user's default locale
     $request = $event->getRequest();
     if (!$request->hasPreviousSession()) {
         return;
     }
     $currentUser = $this->factory->getUser();
     //set the user's timezone
     if (is_object($currentUser)) {
         $tz = $currentUser->getTimezone();
     }
     if (empty($tz)) {
         $tz = $this->params['default_timezone'];
     }
     date_default_timezone_set($tz);
     if (!($locale = $request->attributes->get('_locale'))) {
         if (is_object($currentUser)) {
             $locale = $currentUser->getLocale();
         }
         if (empty($locale)) {
             $locale = $this->params['locale'];
         }
     }
     $request->setLocale($locale);
     // Set a cookie with session name for CKEditor's filemanager
     $sessionName = $request->cookies->get('mautic_session_name');
     if ($sessionName != session_name()) {
         /** @var \Mautic\CoreBundle\Helper\CookieHelper $cookieHelper */
         $cookieHelper = $this->factory->getHelper('cookie');
         $cookieHelper->setCookie('mautic_session_name', session_name(), null);
     }
 }
示例#16
0
 public function handle(GetResponseEvent $evt)
 {
     $request = $evt->getRequest();
     // check if username is set, let it override
     if ($request->get('_username')) {
         return;
     }
     // check if another token exists, then skip
     if ($this->context->getToken() && !$this->context->getToken() instanceof SspiUserToken) {
         return;
     }
     $server = $request->server;
     $remote_user = $server->get('REMOTE_USER');
     if (!$remote_user) {
         return;
     }
     $cred = explode('\\', $remote_user);
     if (count($cred) == 1) {
         array_unshift($cred, "unknown");
     }
     $token = new SspiUserToken();
     $token->setUser($cred[1]);
     try {
         $token = $this->manager->authenticate($token);
         $this->context->setToken($token);
         return;
     } catch (AuthenticationException $failed) {
         $this->context->setToken(null);
         return;
     }
 }
示例#17
0
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->tokenStorage->getToken()) {
         return;
     }
     $request = $event->getRequest();
     $token = new PluginToken($this->providerKey, $request->get('integration', null));
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         if ($authToken instanceof PluginToken) {
             $response = $authToken->getResponse();
             if ($authToken->isAuthenticated()) {
                 $this->tokenStorage->setToken($authToken);
                 if ('api' != $this->providerKey) {
                     $response = $this->onSuccess($request, $authToken, $response);
                 }
             } elseif (empty($response)) {
                 throw new AuthenticationException('mautic.user.auth.error.invalidlogin');
             }
         }
     } catch (AuthenticationException $exception) {
         if ('api' != $this->providerKey) {
             $response = $this->onFailure($request, $exception);
         }
     }
     if ($response) {
         $event->setResponse($response);
     }
 }
示例#18
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     // initialize the context that is also used by the generator (assuming matcher and generator share the same context instance)
     // we call setRequest even if most of the time, it has already been done to keep compatibility
     // with frameworks which do not use the Symfony service container
     $this->setRequest($request);
     if ($request->attributes->has('_controller')) {
         // routing is already done
         return;
     }
     // add attributes based on the request (routing)
     try {
         // matching a request is more powerful than matching a URL path + context, so try that first
         if ($this->matcher instanceof RequestMatcherInterface) {
             $parameters = $this->matcher->matchRequest($request);
         } else {
             $parameters = $this->matcher->match($request->getPathInfo());
         }
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->parametersToString($parameters)));
         }
         $request->attributes->add($parameters);
         unset($parameters['_route']);
         unset($parameters['_controller']);
         $request->attributes->set('_route_params', $parameters);
     } catch (ResourceNotFoundException $e) {
         $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
         throw new NotFoundHttpException($message, $e);
     } catch (MethodNotAllowedException $e) {
         $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods())));
         throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
     }
 }
示例#19
0
 /**
  * Determines and sets the Request format.
  *
  * @param GetResponseEvent $event The event
  *
  * @throws NotAcceptableHttpException
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
         return;
     }
     try {
         $format = $request->getRequestFormat(null);
         if (null === $format) {
             $accept = $this->formatNegotiator->getBest('');
             if (null !== $accept && 0.0 < $accept->getQuality()) {
                 $format = $request->getFormat($accept->getType());
                 if (null !== $format) {
                     $request->attributes->set('media_type', $accept->getValue());
                 }
             }
         }
         if (null === $format) {
             if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) {
                 throw new NotAcceptableHttpException('No matching accepted Response format could be determined');
             }
             return;
         }
         $request->setRequestFormat($format);
     } catch (StopFormatListenerException $e) {
         // nothing to do
     }
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onRequest(GetResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         return;
     }
     $this->requestLogger->logRequest($event->getRequest());
 }
 /**
  * Handles basic authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (false === ($username = $request->headers->get('PHP_AUTH_USER', false))) {
         return;
     }
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) {
             return;
         }
     }
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Basic Authentication Authorization header found for user "%s"', $username));
     }
     try {
         $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey));
         $this->securityContext->setToken($token);
     } catch (AuthenticationException $e) {
         $token = $this->securityContext->getToken();
         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
             $this->securityContext->setToken(null);
         }
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $e->getMessage()));
         }
         if ($this->ignoreFailure) {
             return;
         }
         $event->setResponse($this->authenticationEntryPoint->start($request, $e));
     }
 }
 /**
  * Handles pre-authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public final function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Checking secure context token: %s', $this->securityContext->getToken()));
     }
     try {
         list($user, $credentials) = $this->getPreAuthenticatedData($request);
     } catch (BadCredentialsException $exception) {
         $this->clearToken($exception);
         return;
     }
     if (null !== ($token = $this->securityContext->getToken())) {
         if ($token instanceof PreAuthenticatedToken && $this->providerKey == $token->getProviderKey() && $token->isAuthenticated() && $token->getUsername() === $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->info(sprintf('Authentication success: %s', $token));
         }
         $this->securityContext->setToken($token);
         if (null !== $this->dispatcher) {
             $loginEvent = new InteractiveLoginEvent($request, $token);
             $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
         }
     } catch (AuthenticationException $failed) {
         $this->clearToken($failed);
     }
 }
 /**
  * Action performed on kernel response event.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The response event.
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     $event->getRequest()->server->set('REMOTE_ADDR', $this->fakeIp);
 }
示例#24
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);
 }
 public function checkRoutePattern(GetResponseEvent $event)
 {
     if (preg_match(static::$NOSESSION_ROUTES, $event->getRequest()->getPathInfo())) {
         $this->app['session.test'] = true;
         $this->sessionCookieEnabled = false;
     }
 }
示例#26
0
 /**
  * Logs master requests on event KernelEvents::REQUEST.
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $this->logRequest($event->getRequest());
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         // don't do anything if it's not the master request
         return;
     }
     $token = $this->context->getToken();
     if (is_null($token)) {
         return;
     }
     $_route = $event->getRequest()->attributes->get('_route');
     if ($this->context->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
         if (!$token->getUser() instanceof PersonInterface) {
             // We don't have a PersonInterface... Nothing to do here.
             return;
         }
         if ($_route == 'lc_home' || $_route == 'fos_user_security_login') {
             $key = '_security.main.target_path';
             #where "main" is your firewall name
             //check if the referer session key has been set
             if ($this->session->has($key)) {
                 //set the url based on the link they were trying to access before being authenticated
                 $url = $this->session->get($key);
                 //remove the session key
                 $this->session->remove($key);
             } else {
                 $url = $this->router->generate('lc_dashboard');
             }
             $event->setResponse(new RedirectResponse($url));
         } else {
             $this->checkUnconfirmedEmail();
         }
     }
 }
 function it_sets_locale_to_locale_manager(GetResponseEvent $event, Request $request, LocaleManager $localeManager)
 {
     $event->getRequest()->willReturn($request);
     $request->get('locale')->willReturn('pl');
     $localeManager->setLocale('pl')->shouldBeCalled();
     $this->onKernelRequest($event);
 }
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($this->options['post_only'] && !$request->isMethod('POST')) {
         $event->setResponse(new JsonResponse('invalid method', 405));
         return;
     }
     if ($this->options['post_only']) {
         $username = trim($request->request->get($this->options['username_parameter'], null, true));
         $password = $request->request->get($this->options['password_parameter'], null, true);
     } else {
         $username = trim($request->get($this->options['username_parameter'], null, true));
         $password = $request->get($this->options['password_parameter'], null, true);
     }
     try {
         $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
         $this->securityContext->setToken($token);
         $response = $this->onSuccess($event, $request, $token);
     } catch (AuthenticationException $e) {
         if (null == $this->failureHandler) {
             throw $e;
         }
         $response = $this->onFailure($event, $request, $e);
     }
     $event->setResponse($response);
 }
示例#30
0
 /**
  * Logs master requests on event KernelEvents::REQUEST
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $this->logRequest($event->getRequest());
 }