You are here

public function BootSubscriber::onEvent in Bakery Single Sign-On System 8.2

On boot event we need to test the cookie.

File

src/EventSubscriber/BootSubscriber.php, line 87
For Boot event subscribe.

Class

BootSubscriber
For handling chocolatechip cookie on boot.

Namespace

Drupal\bakery\EventSubscriber

Code

public function onEvent(GetResponseEvent $event) {
  try {
    $cookie = $this->kitchen
      ->taste(Kitchen::CHOCOLATE_CHIP);
  } catch (MissingKeyException $e) {

    // Continue below to clean up.
    $cookie = FALSE;
  }

  // Continue if this is a valid cookie.
  // That only happens for users who have a current valid session on the
  // master site.
  if ($cookie) {

    // Detect SSO cookie mismatch if there is already a valid session and
    // force logout.
    if ($this->currentUser
      ->id() && $cookie['name'] !== $this->currentUser
      ->getAccountName()) {
      user_logout();
      $event
        ->setResponse(new RedirectResponse('/'));
      return;
    }
    if ($this->bakeryService
      ->isMain()) {
      if ($this->currentUser
        ->isAuthenticated()) {

        // Bake a fresh cookie. Yum.
        $this->kitchen
          ->bake(ChocolateChip::fromData($cookie));
      }
      else {
        $this->kitchen
          ->eat(Kitchen::CHOCOLATE_CHIP);
      }
    }
    elseif ($this->currentUser
      ->isAnonymous()) {
      $this
        ->somethingAnonymous($event, $cookie);
    }
  }
  else {

    // Eat the bad cookie. Burp.
    $this->kitchen
      ->eat(Kitchen::CHOCOLATE_CHIP);

    // Log out users that have lost their SSO cookie, with the exception of
    // UID 1 and any applied roles with permission to bypass.
    if ($this->currentUser
      ->id() > 1 && !$this->currentUser
      ->hasPermission('bypass bakery')) {
      $this
        ->getLogger('bakery')
        ->notice('Logging out the user with the bad cookie.', []);
      user_logout();

      // Maybe detect destinations and try to move them along?
      $event
        ->setResponse(new RedirectResponse('/'));
    }
  }
}