You are here

public function CasRedirector::buildRedirectResponse in CAS 8

Same name and namespace in other branches
  1. 2.x src/Service/CasRedirector.php \Drupal\cas\Service\CasRedirector::buildRedirectResponse()

Determine login URL response.

Parameters

\Drupal\cas\CasRedirectData $data: Data used to generate redirector.

bool $force: True implies that you always want to generate a redirector as occurs with the ForceRedirectController. False implies redirector is controlled by the allow_redirect property in the CasRedirectData object.

Return value

\Drupal\Core\Routing\TrustedRedirectResponse|\Drupal\cas\CasRedirectResponse|null The RedirectResponse or NULL if a redirect shouldn't be done.

File

src/Service/CasRedirector.php, line 82

Class

CasRedirector
Class CasRedirector.

Namespace

Drupal\cas\Service

Code

public function buildRedirectResponse(CasRedirectData $data, $force = FALSE) {
  $response = NULL;
  $casServerConfig = CasServerConfig::createFromModuleConfig($this->settings);

  // Dispatch an event that allows modules to alter or prevent the redirect,
  // or to change the CAS server that we're redirected to.
  $pre_redirect_event = new CasPreRedirectEvent($data, $casServerConfig);
  $this->eventDispatcher
    ->dispatch(CasHelper::EVENT_PRE_REDIRECT, $pre_redirect_event);

  // Build the service URL, which is where the CAS server will send users
  // back to after authenticating them. We always send users back to our main
  // service controller, but there can be additional query params to attach
  // to that request as well.
  $service_parameters = $data
    ->getAllServiceParameters();
  $parameters = $data
    ->getAllParameters();
  $parameters['service'] = $this->urlGenerator
    ->generate('cas.service', $service_parameters, UrlGeneratorInterface::ABSOLUTE_URL);
  $login_url = $casServerConfig
    ->getServerBaseUrl() . 'login?' . UrlHelper::buildQuery($parameters);

  // Get the redirection response.
  if ($force || $data
    ->willRedirect()) {

    // $force implies we are on the /cas url or equivalent, so we
    // always want to redirect and data is always cacheable.
    if (!$force && !$data
      ->getIsCacheable()) {
      return new CasRedirectResponse($login_url);
    }
    else {
      $cacheable_metadata = new CacheableMetadata();

      // Add caching metadata from CasRedirectData.
      if (!empty($data
        ->getCacheTags())) {
        $cacheable_metadata
          ->addCacheTags($data
          ->getCacheTags());
      }
      if (!empty($data
        ->getCacheContexts())) {
        $cacheable_metadata
          ->addCacheContexts($data
          ->getCacheContexts());
      }
      $response = new TrustedRedirectResponse($login_url);
      $response
        ->addCacheableDependency($cacheable_metadata);
    }
    $this->casHelper
      ->log(LogLevel::DEBUG, "Cas redirecting to %url", [
      '%url' => $login_url,
    ]);
  }
  return $response;
}