getRoles example

    $this->adminUser = $this->drupalCreateUser([
      'administer blocks',
      'access administration pages',
    ]);
    $this->drupalLogin($this->adminUser);

    // Create additional users to test caching modes.     $this->normalUser = $this->drupalCreateUser();
    $this->normalUserAlt = $this->drupalCreateUser();
    // Sync the roles, since drupalCreateUser() creates separate roles for     // the same permission sets.     $this->normalUserAlt->roles = $this->normalUser->getRoles();
    $this->normalUserAlt->save();

    // Enable our test block.     $this->block = $this->drupalPlaceBlock('test_cache');
  }

  /** * Tests "user.roles" cache context. */
  public function testCachePerRole() {
    \Drupal::state()->set('block_test.cache_contexts', ['user.roles']);

    

    $format2->save();

    // Create a third text format.     $format3 = FilterFormat::create([
      'format' => mb_strtolower($this->randomMachineName()),
      'name' => '3_' . $this->randomMachineName(),
    ]);
    $format3->save();

    // Grant access to both formats to the user.     $roles = $this->webUser->getRoles();
    $rid = $roles[0];
    user_role_grant_permissions($rid[
      $format1->getPermissionName(),
      $format2->getPermissionName(),
      $format3->getPermissionName(),
    ]);

    // Create a field with multiple formats allowed.     $field_name = mb_strtolower($this->randomMachineName());
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      
$role_storage->create(['id' => 'test_role_two', 'label' => 'Test role 2'])->save();
    $role_storage->create(['id' => 'test_role_three', 'label' => 'Test role 3'])->save();

    $values = [
      'uid' => 1,
      'roles' => ['test_role_one'],
    ];
    $user = User::create($values);

    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one']$user->getRoles());

    $account = $user->addRole('test_role_one');
    $this->assertSame($user$account);
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one']$user->getRoles());

    $user->addRole('test_role_two');
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one', 'test_role_two']$user->getRoles());

    
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);

    $this->drupalGet('taxonomy/term/' . $term->id());
    $this->assertSession()->pageTextContains($term->label());
    $this->assertSession()->pageTextContains($node->label());

    \Drupal::service('module_installer')->install(['language', 'content_translation']);
    ConfigurableLanguage::createFromLangcode('ur')->save();
    // Enable translation for the article content type and ensure the change is     // picked up.     \Drupal::service('content_translation.manager')->setEnabled('node', 'article', TRUE);
    $roles = $this->adminUser->getRoles(TRUE);
    Role::load(reset($roles))
      ->grantPermission('create content translations')
      ->grantPermission('translate any entity')
      ->save();

    $edit['title[0][value]'] = $translated_title = $this->randomMachineName();

    $this->drupalGet('node/' . $node->id() . '/translations/add/en/ur');
    $this->submitForm($edit, 'Save (this translation)');

    $this->drupalGet('taxonomy/term/' . $term->id());
    


  /** * Grants given user permission to create content of given type. * * @param \Drupal\Core\Session\AccountInterface $account * User to grant permission to. * @param string $content_type_id * Content type ID. */
  protected function grantUserPermissionToCreateContentOfType(AccountInterface $account$content_type_id) {
    $role_ids = $account->getRoles(TRUE);
    /** @var \Drupal\user\RoleInterface $role */
    $role_id = reset($role_ids);
    $role = Role::load($role_id);
    $role->grantPermission(sprintf('create %s content', $content_type_id));
    $role->grantPermission(sprintf('edit any %s content', $content_type_id));
    $role->grantPermission(sprintf('delete any %s content', $content_type_id));
    $role->save();
  }

}
$this->assertSession()->pageTextNotContains($unpublished->label());
    $this->assertSession()->pageTextContains($published->label());
    $this->assertSession()->linkExists('My recent content', 0, 'User tab shows up on the global tracker page.');

    // Assert cache contexts, specifically the pager and node access contexts.     $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user.node_grants:view', 'user']);
    // Assert cache tags for the action/tabs blocks, visible node, and node list     // cache tag.     $expected_tags = Cache::mergeTags($published->getCacheTags()$published->getOwner()->getCacheTags());
    // Because the 'user.permissions' cache context is being optimized away.     $role_tags = [];
    foreach ($this->user->getRoles() as $rid) {
      $role_tags[] = "config:user.role.$rid";
    }
    $expected_tags = Cache::mergeTags($expected_tags$role_tags);
    $block_tags = [
      'block_view',
      'local_task',
      'config:block.block.page_actions_block',
      'config:block.block.page_tabs_block',
      'config:block_list',
    ];
    $expected_tags = Cache::mergeTags($expected_tags$block_tags);
    
/** * {@inheritdoc} */
  public function getCacheableMetadata() {
    $cacheable_metadata = new CacheableMetadata();

    // The permissions hash changes when:     // - a user is updated to have different roles;     $tags = ['user:' . $this->user->id()];
    // - a role is updated to have different permissions.     foreach ($this->user->getRoles() as $rid) {
      $tags[] = "config:user.role.$rid";
    }

    return $cacheable_metadata->setCacheTags($tags);
  }

}
    $this->drupalGet('search/node');
    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextContains('Your search yielded no results.');
  }

  /** * Verify access rules for comment indexing with different permissions. */
  public function testSearchResultsCommentAccess() {
    $comment_body = 'Test comment body';
    $this->commentSubject = 'Test comment subject';
    $roles = $this->adminUser->getRoles(TRUE);
    $this->adminRole = $roles[0];

    // Create a node.     // Make preview optional.     $field = FieldConfig::loadByName('node', 'article', 'comment');
    $field->setSetting('preview', DRUPAL_OPTIONAL);
    $field->save();
    $this->node = $this->drupalCreateNode(['type' => 'article']);

    // Post a comment using 'Full HTML' text format.     $edit_comment = [];
    


        return $this->loadUser($identifier$entry);
    }

    public function refreshUser(UserInterface $user): UserInterface
    {
        if (!$user instanceof LdapUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        return new LdapUser($user->getEntry()$user->getUserIdentifier()$user->getPassword()$user->getRoles()$user->getExtraFields());
    }

    /** * @final */
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
    {
        if (!$user instanceof LdapUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        
public function isEqualTo(UserInterface $user): bool
    {
        if (!$user instanceof self) {
            return false;
        }

        if ($this->getPassword() !== $user->getPassword()) {
            return false;
        }

        $currentRoles = array_map('strval', (array) $this->getRoles());
        $newRoles = array_map('strval', (array) $user->getRoles());
        $rolesChanged = \count($currentRoles) !== \count($newRoles) || \count($currentRoles) !== \count(array_intersect($currentRoles$newRoles));
        if ($rolesChanged) {
            return false;
        }

        if ($this->getUserIdentifier() !== $user->getUserIdentifier()) {
            return false;
        }

        if ($this->isEnabled() !== $user->isEnabled()) {
            
$this->userFloodControl->clear('user.http_login', $this->getLoginFloodIdentifier($request$credentials['name']));
      /** @var \Drupal\user\UserInterface $user */
      $user = $this->userStorage->load($uid);
      $this->userLoginFinalize($user);

      // Send basic metadata about the logged in user.       $response_data = [];
      if ($user->get('uid')->access('view', $user)) {
        $response_data['current_user']['uid'] = $user->id();
      }
      if ($user->get('roles')->access('view', $user)) {
        $response_data['current_user']['roles'] = $user->getRoles();
      }
      if ($user->get('name')->access('view', $user)) {
        $response_data['current_user']['name'] = $user->getAccountName();
      }
      $response_data['csrf_token'] = $this->csrfToken->get('rest');

      $logout_route = $this->routeProvider->getRouteByName('user.logout.http');
      // Trim '/' off path to match \Drupal\Core\Access\CsrfAccessCheck.       $logout_path = ltrim($logout_route->getPath(), '/');
      $response_data['logout_token'] = $this->csrfToken->get($logout_path);

      

function hook_shortcut_default_set(\Drupal\Core\Session\AccountInterface $account) {
  // Use a special set of default shortcuts for administrators only.   $roles = \Drupal::entityTypeManager()->getStorage('user_role')->loadByProperties(['is_admin' => TRUE]);
  $user_admin_roles = array_intersect(array_keys($roles)$account->getRoles());
  if ($user_admin_roles) {
    return 'admin-shortcuts';
  }
}

/** * @} End of "addtogroup hooks". */

        $tokenAttributes = 2 < \func_num_args() ? func_get_arg(2) : [];

        if (!interface_exists(UserInterface::class)) {
            throw new \LogicException(sprintf('"%s" requires symfony/security-core to be installed. Try running "composer require symfony/security-core".', __METHOD__));
        }

        if (!$user instanceof UserInterface) {
            throw new \LogicException(sprintf('The first argument of "%s" must be instance of "%s", "%s" provided.', __METHOD__, UserInterface::classget_debug_type($user)));
        }

        $token = new TestBrowserToken($user->getRoles()$user$firewallContext);
        $token->setAttributes($tokenAttributes);
        // required for compatibility with Symfony 5.4         if (method_exists($token, 'isAuthenticated')) {
            $token->setAuthenticated(true, false);
        }

        $container = $this->getContainer();
        $container->get('security.untracked_token_storage')->setToken($token);

        if (!$container->has('session.factory')) {
            return $this;
        }
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->adminUser = $this->drupalCreateUser([
      'administer permissions',
    ]);

    // Find the new role ID.     $all_rids = $this->adminUser->getRoles();
    unset($all_rids[array_search(RoleInterface::AUTHENTICATED_ID, $all_rids)]);
    $this->rid = reset($all_rids);
  }

  /** * Tests the dummy checkboxes added to the permissions page. */
  public function testPermissionCheckboxes() {
    $this->drupalLogin($this->adminUser);
    $this->drupalGet('admin/people/permissions');

    
$this->assertEquals($user_a->getAccountName()$result[0]->find('xpath', '/td[2]/a')->getText(), 'Filter by username returned the right user.');

    // Filter the users by permission 'administer taxonomy'.     $this->drupalGet('admin/people', ['query' => ['permission' => 'administer taxonomy']]);

    // Check if the correct users show up.     $this->assertSession()->elementNotExists('xpath', static::getLinkSelectorForUser($user_a));
    $this->assertSession()->elementExists('xpath', static::getLinkSelectorForUser($user_b));
    $this->assertSession()->elementExists('xpath', static::getLinkSelectorForUser($user_c));

    // Filter the users by role. Grab the system-generated role name for User C.     $roles = $user_c->getRoles();
    unset($roles[array_search(RoleInterface::AUTHENTICATED_ID, $roles)]);
    $this->drupalGet('admin/people', ['query' => ['role' => reset($roles)]]);

    // Check if the correct users show up when filtered by role.     $this->assertSession()->elementNotExists('xpath', static::getLinkSelectorForUser($user_a));
    $this->assertSession()->elementNotExists('xpath', static::getLinkSelectorForUser($user_b));
    $this->assertSession()->elementExists('xpath', static::getLinkSelectorForUser($user_c));

    // Test blocking of a user.     $account = $user_storage->load($user_c->id());
    $this->assertTrue($account->isActive(), 'User C not blocked');
    
Home | Imprint | This part of the site doesn't use cookies.