You are here

public function SessionLimit::onKernelRequest in Session Limit 2.x

Same name and namespace in other branches
  1. 8 src/Services/SessionLimit.php \Drupal\session_limit\Services\SessionLimit::onKernelRequest()

Event listener, on executing a Kernel request.

Check the users active sessions and invoke a session collision if it is higher than the configured limit.

File

src/Services/SessionLimit.php, line 157

Class

SessionLimit

Namespace

Drupal\session_limit\Services

Code

public function onKernelRequest() {

  // Show session messages to the user if they have been logged out.
  if (isset($_SESSION['messages'])) {
    $session_messages = $_SESSION['messages'];
    foreach ($session_messages as $severity => $message_object) {
      foreach ($message_object as $message) {
        \Drupal::messenger()
          ->addMessage($message, $severity);
      }
    }

    // Remove messages from session so that it only displays once.
    unset($_SESSION['messages']);
  }

  /** @var SessionLimitBypassEvent $bypassEvent */
  $bypassEvent = $this
    ->getEventDispatcher()
    ->dispatch('session_limit.bypass', new SessionLimitBypassEvent());

  // Check the result of the event to see if we should bypass.
  if ($bypassEvent
    ->shouldBypass()) {
    return;
  }
  $active_sessions = $this
    ->getUserActiveSessionCount($this
    ->getCurrentUser());
  $max_sessions = $this
    ->getUserMaxSessions($this
    ->getCurrentUser());
  if ($max_sessions > 0 && $active_sessions > $max_sessions) {
    $collisionEvent = new SessionLimitCollisionEvent(session_id(), $this
      ->getCurrentUser(), $active_sessions, $max_sessions);
    $this
      ->getEventDispatcher()
      ->dispatch('session_limit.collision', $collisionEvent);
  }
  else {

    // force checking this twice as there's a race condition around
    // sessionId creation see issue #1176412.
    // @todo accessing the $_SESSION super global is bad.
    if (!isset($_SESSION['session_limit_checkonce'])) {
      $_SESSION['session_limit_checkonce'] = TRUE;
    }
    else {

      // mark sessionId as verified to bypass this in future.
      $_SESSION['session_limit'] = TRUE;
    }
  }
}