You are here

function SessionTest::testSessionSaveRegenerate in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/modules/system/src/Tests/Session/SessionTest.php \Drupal\system\Tests\Session\SessionTest::testSessionSaveRegenerate()

Tests for \Drupal\Core\Session\WriteSafeSessionHandler::setSessionWritable() ::isSessionWritable and \Drupal\Core\Session\SessionManager::regenerate().

File

core/modules/system/src/Tests/Session/SessionTest.php, line 32
Contains \Drupal\system\Tests\Session\SessionTest.

Class

SessionTest
Drupal session handling tests.

Namespace

Drupal\system\Tests\Session

Code

function testSessionSaveRegenerate() {
  $session_handler = $this->container
    ->get('session_handler.write_safe');
  $this
    ->assertTrue($session_handler
    ->isSessionWritable(), 'session_handler->isSessionWritable() initially returns TRUE.');
  $session_handler
    ->setSessionWritable(FALSE);
  $this
    ->assertFalse($session_handler
    ->isSessionWritable(), '$session_handler->isSessionWritable() returns FALSE after disabling.');
  $session_handler
    ->setSessionWritable(TRUE);
  $this
    ->assertTrue($session_handler
    ->isSessionWritable(), '$session_handler->isSessionWritable() returns TRUE after enabling.');

  // Test session hardening code from SA-2008-044.
  $user = $this
    ->drupalCreateUser();

  // Enable sessions.
  $this
    ->sessionReset($user
    ->id());

  // Make sure the session cookie is set as HttpOnly.
  $this
    ->drupalLogin($user);
  $this
    ->assertTrue(preg_match('/HttpOnly/i', $this
    ->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.');
  $this
    ->drupalLogout();

  // Verify that the session is regenerated if a module calls exit
  // in hook_user_login().
  $user->name = 'session_test_user';
  $user
    ->save();
  $this
    ->drupalGet('session-test/id');
  $matches = array();
  preg_match('/\\s*session_id:(.*)\\n/', $this
    ->getRawContent(), $matches);
  $this
    ->assertTrue(!empty($matches[1]), 'Found session ID before logging in.');
  $original_session = $matches[1];

  // We cannot use $this->drupalLogin($user); because we exit in
  // session_test_user_login() which breaks a normal assertion.
  $edit = array(
    'name' => $user
      ->getUsername(),
    'pass' => $user->pass_raw,
  );
  $this
    ->drupalPostForm('user/login', $edit, t('Log in'));
  $this
    ->drupalGet('user');
  $pass = $this
    ->assertText($user
    ->getUsername(), format_string('Found name: %name', array(
    '%name' => $user
      ->getUsername(),
  )), 'User login');
  $this->_logged_in = $pass;
  $this
    ->drupalGet('session-test/id');
  $matches = array();
  preg_match('/\\s*session_id:(.*)\\n/', $this
    ->getRawContent(), $matches);
  $this
    ->assertTrue(!empty($matches[1]), 'Found session ID after logging in.');
  $this
    ->assertTrue($matches[1] != $original_session, 'Session ID changed after login.');
}