You are here

public function DomainSubscriber::onKernelRequestDomain in Domain Access 8

Sets the domain context of the request.

This method also determines the redirect status for the http request.

Specifically, here we determine if a redirect is required. That happens in one of two cases: an unauthorized request to an inactive domain is made; a domain alias is set to redirect to its primary domain record.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseEvent $event: The Event to process.

See also

domain_alias_domain_request_alter

File

domain/src/EventSubscriber/DomainSubscriber.php, line 90

Class

DomainSubscriber
Sets the domain context for an http request.

Namespace

Drupal\domain\EventSubscriber

Code

public function onKernelRequestDomain(GetResponseEvent $event) {

  // Negotiate the request and set domain context.

  /** @var \Drupal\domain\DomainInterface $domain */
  if ($domain = $this->domainNegotiator
    ->getActiveDomain(TRUE)) {
    $hostname = $domain
      ->getHostname();
    $domain_url = $domain
      ->getUrl();
    if ($domain_url) {
      $redirect_status = $domain
        ->getRedirect();
      $path = trim($event
        ->getRequest()
        ->getPathInfo(), '/');

      // If domain negotiation asked for a redirect, issue it.
      if (is_null($redirect_status) && $this->accessCheck
        ->checkPath($path)) {

        // Else check for active domain or inactive access.

        /** @var \Drupal\Core\Access\AccessResult $access */
        $access = $this->accessCheck
          ->access($this->account);

        // If the access check fails, reroute to the default domain.
        // Note that Allowed, Neutral, and Failed are the options here.
        // We insist on Allowed.
        if (!$access
          ->isAllowed()) {

          /** @var \Drupal\domain\DomainInterface $default */
          $default = $this->domainStorage
            ->loadDefaultDomain();
          $domain_url = $default
            ->getUrl();
          $redirect_status = 302;
          $hostname = $default
            ->getHostname();
        }
      }
    }
    if (!empty($redirect_status)) {

      // Pass a redirect if necessary.
      if (DomainRedirectResponse::checkTrustedHost($hostname)) {
        $response = new TrustedRedirectResponse($domain_url, $redirect_status);
      }
      else {

        // If the redirect is not to a registered hostname, reject the
        // request.
        $response = new Response('The provided host name is not a valid redirect.', 401);
      }
      $event
        ->setResponse($response);
    }
  }
}