Esempio n. 1
0
 public function doRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
         return;
     }
     $prefix = ConfigQuery::read("back_office_path");
     $defaultEnabled = intval(ConfigQuery::read("back_office_path_default_enabled", "1"));
     $pathInfo = $event->getRequest()->getPathInfo();
     $url = $event->getRequest()->server->get('REQUEST_URI');
     // Discard the default /admin URL
     $isValid = 1 !== $defaultEnabled && strpos($pathInfo, '/' . BackOfficePath::DEFAULT_THELIA_PREFIX) === 0 && $prefix !== null && $prefix !== "";
     if ($isValid) {
         /** @var \Symfony\Component\Routing\RequestContext $context */
         $context = $event->getKernel()->getContainer()->get('request.context');
         $context->fromRequest($event->getRequest());
         throw new NotFoundHttpException();
     }
     // Check if the URL is an backOffice URL
     $isValid = strpos($pathInfo, '/' . $prefix) === 0 && $prefix !== null && $prefix !== "";
     if ($isValid) {
         $newUrl = $this->replaceUrl($url, $prefix, BackOfficePath::DEFAULT_THELIA_PREFIX);
         $event->getRequest()->server->set('REQUEST_URI', $newUrl);
         $event->getRequest()->initialize($event->getRequest()->query->all(), $event->getRequest()->request->all(), $event->getRequest()->attributes->all(), $event->getRequest()->cookies->all(), $event->getRequest()->files->all(), $event->getRequest()->server->all(), $event->getRequest()->getContent());
     }
 }
 /**
  * Set the username from the security context by listening on core.request
  *
  * @param GetResponseEvent $event
  */
 public function onCoreRequest(GetResponseEvent $event)
 {
     $securityContext = $event->getKernel()->getContainer()->get('security.context', ContainerInterface::NULL_ON_INVALID_REFERENCE);
     if (null !== $securityContext && null !== $securityContext->getToken() && $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
         $this->setUsername($this->securityContext->getToken()->getUsername());
     }
 }
Esempio n. 3
0
 /**
  * Initiate session if not available then reads the SecurityContext from it.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $application = $event->getKernel()->getApplication();
     if (null !== $application && false === $request->hasSession()) {
         $container = $application->getContainer();
         $event->getRequest()->setSession($container->get('bb_session'));
     }
     parent::handle($event);
 }
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $securityAuthRealm = $this->container->get('security.authRealm');
     $request = $event->getRequest();
     $uri = $request->getRequestUri();
     foreach ($securityAuthRealm as $authRealm => $realmConfig) {
         if (isset($realmConfig['authRoute']) && preg_match('#' . $realmConfig['authRoute'] . '#', $uri)) {
             $event->setResponse($event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, true));
             return;
         }
     }
 }
Esempio n. 5
0
 /**
  * Initiate session if not available then reads the SecurityContext from it.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $application = $event->getKernel()->getApplication();
     if (null !== $application && false === $request->hasSession()) {
         // Don't need to check if container has service with id `bb_session` cause we declared it as synthetic
         if (null === $application->getContainer()->get('bb_session')) {
             $application->getContainer()->set('bb_session', $application->getSession());
         }
         $application->getContainer()->get('bb_session')->start();
         $application->info("Session started");
         $event->getRequest()->setSession($application->getContainer()->get('bb_session'));
     }
     parent::handle($event);
 }
 public function handle(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     if ($request->hasSession()) {
         return;
     }
     if (null !== ($application = $event->getKernel()->getApplication())) {
         if (!$application->getContainer()->has('bb_session')) {
             $application->getContainer()->set('bb_session', $application->getSession());
         }
         $application->getContainer()->get('bb_session')->start();
         $application->debug("Session started");
         $request->setSession($application->getContainer()->get('bb_session'));
     }
 }
 /**
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  */
 public function onKernelRequestForward(GetResponseEvent $event)
 {
     if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) {
         $request = $event->getRequest();
         if ($request->attributes->get('needsForward') && $request->attributes->has('semanticPathinfo')) {
             $semanticPathinfo = $request->attributes->get('semanticPathinfo');
             $request->attributes->remove('needsForward');
             $forwardRequest = Request::create($semanticPathinfo, $request->getMethod(), $request->getMethod() === 'POST' ? $request->request->all() : $request->query->all(), $request->cookies->all(), $request->files->all(), $request->server->all(), $request->getContent());
             $forwardRequest->attributes->add($request->attributes->all());
             // Not forcing HttpKernelInterface::SUB_REQUEST on purpose since we're very early here
             // and we need to bootstrap essential stuff like sessions.
             $event->setResponse($event->getKernel()->handle($forwardRequest));
             $event->stopPropagation();
             if (isset($this->logger)) {
                 $this->logger->info("URLAlias made request to be forwarded to {$semanticPathinfo}", array('pathinfo' => $request->getPathInfo()));
             }
         }
     }
 }
Esempio n. 8
0
 /**
  * Handle authorization by HTTP Authorization header     *
  * <code>Authorization: BPI pk="public_key", token="token"</code>
  *
  * Or by query string
  * <code>http://example.com/page?_authorization[pk]=public_key&_authorization[token]=token</code>
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  * @throws AuthenticationException
  */
 public function handle(GetResponseEvent $event)
 {
     try {
         if ($this->container->get('kernel')->getEnvironment() == 'test_skip_auth') {
             return $this->skipAuthorization();
         }
         $request = $event->getRequest();
         $token = new PKUserToken();
         if ($request->isMethod('OPTIONS')) {
             return $this->skipAuthorization();
         }
         if ($request->headers->has('Auth')) {
             if (!preg_match('~BPI agency="(?<agency>[^"]+)", token="(?<token>[^"]+)"~i', $request->headers->get('Auth'), $matches)) {
                 throw new AuthenticationException('Authorization credintials required (HTTP Headers)');
             }
             $token->setUser($matches['agency']);
             $token->token = $matches['token'];
         } elseif ($request->query->has('_authorization')) {
             $auth = $request->query->get('_authorization');
             if (empty($auth['agency']) or empty($auth['token'])) {
                 throw new AuthenticationException('Authorization credintials required (GET)');
             }
             $token->setUser($auth['agency']);
             $token->token = $auth['token'];
         } else {
             throw new AuthenticationException('Authorization required (none)');
         }
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         //simulate kernel.view event to be able REST response listener do their job
         $view = new \FOS\RestBundle\View\View($failed->getMessage(), 401);
         $controller_result_event = new GetResponseForControllerResultEvent($event->getKernel(), $request, $event->getRequestType(), $view);
         $view_listener = new ViewResponseListener($this->container);
         $view_listener->onKernelView($controller_result_event);
         $event->setResponse($controller_result_event->getResponse());
     }
 }
 private function onFailure(GetResponseEvent $event, Request $request, AuthenticationException $failed)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Authentication request failed: %s', $failed->getMessage()));
     }
     $this->securityContext->setToken(null);
     if (null !== $this->failureHandler) {
         return $this->failureHandler->onAuthenticationFailure($request, $failed);
     }
     if (null === $this->options['failure_path']) {
         $this->options['failure_path'] = $this->options['login_path'];
     }
     if ($this->options['failure_forward']) {
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Forwarding to %s', $this->options['failure_path']));
         }
         $subRequest = $this->httpUtils->createRequest($request, $this->options['failure_path']);
         $subRequest->attributes->set(SecurityContextInterface::AUTHENTICATION_ERROR, $failed);
         return $event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     }
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Redirecting to %s', $this->options['failure_path']));
     }
     $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $failed);
     return $this->httpUtils->createRedirectResponse($request, $this->options['failure_path']);
 }
Esempio n. 10
0
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $kernel = $event->getKernel();
     $request = $event->getRequest();
     $session = $request->getSession();
     /** @var ContainerInterface $container */
     $container = $this->container;
     // Setting container
     Container::setContainer($container);
     // Setting session.
     Container::setSession($request->getSession());
     // Setting database.
     $dbConnection = $container->get('database_connection');
     // Setting DB connection and Doctrine Manager.
     $database = new \Database();
     $database->setConnection($dbConnection);
     $entityManager = $container->get('doctrine')->getManager();
     $database->setManager($entityManager);
     // Setting course tool chain (in order to create tools to a course)
     \CourseManager::setToolList($container->get('chamilo_course.tool_chain'));
     \CourseManager::setEntityManager($entityManager);
     \CourseManager::setCourseManager($container->get('chamilo_core.manager.course'));
     \CourseManager::setCourseSettingsManager($container->get('chamilo_course.settings.manager'));
     Container::$mailer = $container->get('mailer');
     // Setting legacy properties.
     Container::$urlGenerator = $container->get('router');
     Container::$security = $container->get('security.context');
     Container::$translator = $container->get('translator');
     // Setting paths.
     Container::$rootDir = $container->get('kernel')->getRealRootDir();
     Container::$logDir = $container->get('kernel')->getLogDir();
     Container::$dataDir = $container->get('kernel')->getDataDir();
     Container::$tempDir = $container->get('kernel')->getCacheDir();
     Container::$courseDir = $container->get('kernel')->getDataDir();
     //Container::$configDir = $container->get('kernel')->getConfigDir();
     Container::$assets = $container->get('templating.helper.assets');
     Container::$roles = $container->get('security.role_hierarchy');
     // Setting editor
     Container::$htmlEditor = $container->get('chamilo_core.html_editor');
     if (!defined('DEFAULT_DOCUMENT_QUOTA')) {
         $default_quota = api_get_setting('document.default_document_quotum');
         // Just in case the setting is not correctly set
         if (empty($default_quota)) {
             $default_quota = 100000000;
         }
         define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
     }
     // Access URL (multiple URL)
     /** @var \Sonata\PageBundle\Model\SnapshotPageProxy $page */
     $page = $request->get('page');
     if (isset($page) && !is_numeric($page)) {
         $siteId = $page->getSite()->getId();
         $request->getSession()->set('url_info', $page->getSite());
     } else {
         $siteId = 1;
     }
     $request->getSession()->set('url_id', $siteId);
     /*
             // Loading portal settings from DB.
             $settingsRefreshInfo = $em->getRepository('ChamiloCoreBundle:SettingsCurrent')->findOneByVariable('settings_latest_update');
             $settingsLatestUpdate = !empty($settingsRefreshInfo) ? $settingsRefreshInfo->getSelectedValue() : null;
     
             $settings = $session->get('_setting');
     
             if (empty($settings)) {
                 api_set_settings_and_plugins();
             } else {
                 if (isset($settings['settings_latest_update']) &&
                     $settings['settings_latest_update'] != $settingsLatestUpdate
                 ) {
                     api_set_settings_and_plugins();
                 }
             }*/
 }
 private function onFailure(GetResponseEvent $event, Request $request, AuthenticationException $failed)
 {
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Authentication request failed: %s', $failed->getMessage()));
     }
     $this->securityContext->setToken(null);
     if (null !== $this->failureHandler) {
         return $this->failureHandler->onAuthenticationFailure($request, $failed);
     }
     if (null === $this->options['failure_path']) {
         $this->options['failure_path'] = $this->options['login_path'];
     }
     $path = str_replace('{_locale}', $request->getSession()->getLocale(), $this->options['failure_path']);
     if ($this->options['failure_forward']) {
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Forwarding to %s', $path));
         }
         $subRequest = Request::create($path, 'get', array(), $request->cookies->all(), array(), $request->server->all());
         $subRequest->attributes->set(SecurityContextInterface::AUTHENTICATION_ERROR, $failed);
         return $event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     }
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Redirecting to %s', $path));
     }
     $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $failed);
     return new RedirectResponse(0 !== strpos($path, 'http') ? $request->getUriForPath($path) : $path, 302);
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$event->getRequest()->headers->has('link')) {
         return;
     }
     $links = array();
     $header = $event->getRequest()->headers->get('link');
     /*
      * Due to limitations, multiple same-name headers are sent as comma
      * separated values.
      *
      * This breaks those headers into Link headers following the format
      * http://tools.ietf.org/html/rfc2068#section-19.6.2.4
      */
     while (preg_match('/^((?:[^"]|"[^"]*")*?),/', $header, $matches)) {
         $header = trim(substr($header, strlen($matches[0])));
         $links[] = $matches[1];
     }
     if ($header) {
         $links[] = $header;
     }
     $requestMethod = $this->urlMatcher->getContext()->getMethod();
     // The controller resolver needs a request to resolve the controller.
     $stubRequest = new Request();
     foreach ($links as $idx => $link) {
         // Force the GET method to avoid the use of the
         // previous method (LINK/UNLINK)
         $this->urlMatcher->getContext()->setMethod('GET');
         $linkParams = explode(';', trim($link));
         $resourceType = null;
         if (count($linkParams) > 1) {
             $resourceType = trim(preg_replace('/<|>/', '', $linkParams[1]));
             $resourceType = str_replace("\"", "", str_replace("rel=", "", $resourceType));
         }
         $resource = array_shift($linkParams);
         $resource = preg_replace('/<|>/', '', $resource);
         $tempRequest = Request::create($resource);
         try {
             $route = $this->urlMatcher->match($tempRequest->getRequestUri());
         } catch (\Exception $e) {
             // If we don't have a matching route we return the original Link header
             continue;
         }
         if (strpos($route['_route'], 'newscoop_gimme_') === false) {
             return;
         }
         $stubRequest->attributes->replace($route);
         $stubRequest->server = $event->getRequest()->server;
         if (false === ($controller = $this->resolver->getController($stubRequest))) {
             continue;
         }
         $subEvent = new FilterControllerEvent($event->getKernel(), $controller, $stubRequest, HttpKernelInterface::SUB_REQUEST);
         $kernelSubEvent = new GetResponseEvent($event->getKernel(), $stubRequest, HttpKernelInterface::SUB_REQUEST);
         $event->getDispatcher()->dispatch(KernelEvents::REQUEST, $kernelSubEvent);
         $event->getDispatcher()->dispatch(KernelEvents::CONTROLLER, $subEvent);
         $controller = $subEvent->getController();
         $arguments = $this->resolver->getArguments($stubRequest, $controller);
         try {
             $result = call_user_func_array($controller, $arguments);
             // Our api returns objects for single resources
             if (!is_object($result)) {
                 continue;
             }
             $links[$idx] = array('object' => $result, 'resourceType' => $resourceType);
         } catch (\Exception $e) {
             $links[$idx] = array('object' => $e, 'resourceType' => 'exception');
             continue;
         }
     }
     $event->getRequest()->attributes->set('links', $links);
     $this->urlMatcher->getContext()->setMethod($requestMethod);
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     if (!$event->getRequest()->headers->has('link')) {
         return;
     }
     $links = array();
     $header = $event->getRequest()->headers->get('link');
     /*
      * Due to limitations, multiple same-name headers are sent as comma
      * separated values.
      *
      * This breaks those headers into Link headers following the format
      * http://tools.ietf.org/html/rfc2068#section-19.6.2.4
      */
     while (preg_match('/^((?:[^"]|"[^"]*")*?),/', $header, $matches)) {
         $header = trim(substr($header, strlen($matches[0])));
         $links[] = $matches[1];
     }
     if ($header) {
         $links[] = $header;
     }
     $requestMethod = $this->urlMatcher->getContext()->getMethod();
     // Force the GET method to avoid the use of the
     // previous method (LINK/UNLINK)
     $this->urlMatcher->getContext()->setMethod('GET');
     // The controller resolver needs a request to resolve the controller.
     $stubRequest = new Request();
     foreach ($links as $idx => $link) {
         $linkHeader = $this->parseLinkHeader($link);
         $resource = $this->parseResource($linkHeader, $event->getRequest());
         try {
             $route = $this->urlMatcher->match($resource);
         } catch (\Exception $e) {
             // If we don't have a matching route we return
             // the original Link header
             continue;
         }
         $stubRequest->attributes->replace($route);
         if (false === ($controller = $this->resolver->getController($stubRequest))) {
             continue;
         }
         // Make sure @ParamConverter and some other annotations are called
         $subEvent = new FilterControllerEvent($event->getKernel(), $controller, $stubRequest, HttpKernelInterface::SUB_REQUEST);
         $event->getDispatcher()->dispatch(KernelEvents::CONTROLLER, $subEvent);
         $controller = $subEvent->getController();
         $arguments = $this->resolver->getArguments($stubRequest, $controller);
         try {
             $result = call_user_func_array($controller, $arguments);
             $value = is_array($result) ? current($result) : $result;
             if ($linkHeader->hasRel()) {
                 unset($links[$idx]);
                 $links[$linkHeader->getRel()][] = $value;
             } else {
                 $links[$idx] = $value;
             }
         } catch (\Exception $e) {
             continue;
         }
     }
     $event->getRequest()->attributes->set('links', $links);
     $this->urlMatcher->getContext()->setMethod($requestMethod);
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     $kernel = $event->getKernel();
     $request = $event->getRequest();
     $container = $this->container;
 }