UserSession example

$this->form = [
      '#property' => $this->randomMachineName(),
    ];
    $this->formState = new FormState();
    $this->formState->set('example', $this->randomMachineName());
  }

  /** * Tests the form cache with a logged-in user. */
  public function testCacheToken() {
    \Drupal::currentUser()->setAccount(new UserSession(['uid' => 1]));
    \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);

    $cached_form_state = new FormState();
    $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
    $this->assertEquals($this->form['#property']$cached_form['#property']);
    $this->assertNotEmpty($cached_form['#cache_token'], 'Form has a cache token');
    $this->assertEquals($this->formState->get('example')$cached_form_state->get('example'));

    // Test that the form cache isn't loaded when the session/token has changed.     // Change the private key. (We cannot change the session ID because this     // will break the parent site test runner batch.)

class AccountSwitcherTest extends KernelTestBase {

  public function testAccountSwitching() {
    $session_handler = $this->container->get('session_handler.write_safe');
    $user = $this->container->get('current_user');
    $switcher = $this->container->get('account_switcher');
    $original_user = $user->getAccount();
    $original_session_saving = $session_handler->isSessionWritable();

    // Switch to user with uid 2.     $switcher->switchTo(new UserSession(['uid' => 2]));

    // Verify that the active user has changed, and that session saving is     // disabled.     $this->assertEquals(2, $user->id(), 'Switched to user 2.');
    $this->assertFalse($session_handler->isSessionWritable(), 'Session saving is disabled.');

    // Perform a second (nested) user account switch.     $switcher->switchTo(new UserSession(['uid' => 3]));
    $this->assertEquals(3, $user->id(), 'Switched to user 3.');

    // Revert to the user session that was active between the first and second

  protected function createUserSession(array $rids = []$authenticated = FALSE) {
    array_unshift($rids$authenticated ? RoleInterface::AUTHENTICATED_ID : RoleInterface::ANONYMOUS_ID);
    return new UserSession(['roles' => $rids]);
  }

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $roles = [];
    $roles['role_one'] = $this->getMockBuilder('Drupal\user\Entity\Role')
      ->disableOriginalConstructor()
      
$this->isInstalled = FALSE;

    $this->setupBaseUrl();

    $this->prepareDatabasePrefix();

    // Install Drupal test site.     $this->prepareEnvironment();

    // Define information about the user 1 account.     $this->rootUser = new UserSession([
      'uid' => 1,
      'name' => 'admin',
      'mail' => 'admin@example.com',
      'pass_raw' => $this->randomMachineName(),
    ]);

    // If any $settings are defined for this test, copy and prepare an actual     // settings.php, so as to resemble a regular installation.     if (!empty($this->settings)) {
      // Not using File API; a potential error must trigger a PHP warning.       copy(DRUPAL_ROOT . '/sites/default/default.settings.php', DRUPAL_ROOT . '/' . $this->siteDirectory . '/settings.php');
      
$node = $this->createNode(['type' => 'page']);

    /** @var \Drupal\user\RoleInterface $authenticated */
    $authenticated = Role::create([
      'id' => 'authenticated',
      'label' => 'Authenticated',
    ]);
    $authenticated->grantPermission('access content');
    $authenticated->grantPermission('edit any page content');
    $authenticated->save();

    $account = new UserSession([
      'uid' => 2,
      'roles' => ['authenticated'],
    ]);

    $result = $node->access('update', $account, TRUE);
    $this->assertFalse($result->isAllowed());
    $this->assertEqualsCanonicalizing(['user.permissions']$result->getCacheContexts());
    $this->assertEqualsCanonicalizing(['config:workflows.workflow.editorial', 'node:' . $node->id()]$result->getCacheTags());
    $this->assertEquals(CacheBackendInterface::CACHE_PERMANENT, $result->getCacheMaxAge());

    $authenticated->grantPermission('use editorial transition create_new_draft');
    

  public function roleAccessProvider() {
    // Setup two different roles used in the test.     $rid_1 = 'role_test_1';
    $rid_2 = 'role_test_2';

    // Setup one user with the first role, one with the second, one with both     // and one final without any of these two roles.
    $account_1 = new UserSession([
      'uid' => 1,
      'roles' => [$rid_1],
    ]);

    $account_2 = new UserSession([
      'uid' => 2,
      'roles' => [$rid_2],
    ]);

    $account_12 = new UserSession([
      'uid' => 3,
      
$expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
    $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
    $expected_links .= '<li><a href="' . Url::fromRoute('<front>')->toString() . '">' . Html::escape('Front page') . '</a></li>';
    $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . Html::escape('Test route') . '</a></li>';
    $query = ['key' => 'value'];
    $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . Html::escape('Query test route') . '</a></li>';
    $expected_links .= '</ul>';
    $expected = $expected_heading . $expected_links;
    $this->assertThemeOutput('links', $variables$expected);

    // Verify the data- attributes for setting the "active" class on links.     \Drupal::currentUser()->setAccount(new UserSession(['uid' => 1]));
    $variables['set_active_class'] = TRUE;
    $expected_links = '';
    $expected_links .= '<ul id="somelinks">';
    $expected_links .= '<li><a href="' . Url::fromUri('base:a/link')->toString() . '">' . Html::escape('A <link>') . '</a></li>';
    $expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
    $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
    $expected_links .= '<li data-drupal-link-system-path="&lt;front&gt;"><a href="' . Url::fromRoute('<front>')->toString() . '" data-drupal-link-system-path="&lt;front&gt;">' . Html::escape('Front page') . '</a></li>';
    $expected_links .= '<li data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Test route') . '</a></li>';
    $query = ['key' => 'value'];
    $encoded_query = Html::escape(Json::encode($query));
    $expected_links .= '<li data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '" data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Query test route') . '</a></li>';
    
->query('SELECT * FROM {users_field_data} [u] WHERE [u].[uid] = :uid AND [u].[default_langcode] = 1', [':uid' => $uid])
        ->fetchAssoc();

      // Check if the user data was found and the user is active.       if (!empty($values) && $values['status'] == 1) {
        // Add the user's roles.         $rids = $this->connection
          ->query('SELECT [roles_target_id] FROM {user__roles} WHERE [entity_id] = :uid', [':uid' => $values['uid']])
          ->fetchCol();
        $values['roles'] = array_merge([AccountInterface::AUTHENTICATED_ROLE]$rids);

        return new UserSession($values);
      }
    }

    // This is an anonymous session.     return NULL;
  }

  /** * Adds a query parameter to check successful log in redirect URL. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The Event to process. */
    $config->getEditable('system.date')
      ->set('timezone.default', 'Australia/Sydney')
      ->save();
  }

  /** * Initializes user 1 for the site to be installed. */
  protected function initUserSession() {
    $password = $this->randomMachineName();
    // Define information about the user 1 account.     $this->rootUser = new UserSession([
      'uid' => 1,
      'name' => 'admin',
      'mail' => 'admin@example.com',
      'pass_raw' => $password,
      'passRaw' => $password,
      'timezone' => date_default_timezone_get(),
    ]);

    // The child site derives its session name from the database prefix when     // running web tests.     $this->generateSessionName($this->databasePrefix);
  }
Home | Imprint | This part of the site doesn't use cookies.