コード例 #1
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $admin_roles = $this->adminUser->getRoles();
     $admin_role = Role::load(reset($admin_roles));
     $this->grantPermissions($admin_role, ['administer site configuration']);
 }
コード例 #2
0
 /**
  * Ensures that 'user.permissions' cache context is able to define cache tags.
  */
 public function testUserPermissionCacheContextOptimization()
 {
     $user1 = $this->createUser();
     $this->assertEqual($user1->id(), 1);
     $authenticated_user = $this->createUser(['administer permissions']);
     $role = $authenticated_user->getRoles()[1];
     $test_element = ['#cache' => ['keys' => ['test'], 'contexts' => ['user', 'user.permissions']]];
     \Drupal::service('account_switcher')->switchTo($authenticated_user);
     $element = $test_element;
     $element['#markup'] = 'content for authenticated users';
     $output = \Drupal::service('renderer')->renderRoot($element);
     $this->assertEqual($output, 'content for authenticated users');
     // Verify that the render caching is working so that other tests can be
     // trusted.
     $element = $test_element;
     $element['#markup'] = 'this should not be visible';
     $output = \Drupal::service('renderer')->renderRoot($element);
     $this->assertEqual($output, 'content for authenticated users');
     // Even though the cache contexts have been optimized to only include 'user'
     // cache context, the element should have been changed because
     // 'user.permissions' cache context defined a cache tags for permission
     // changes, which should have bubbled up for the element when it was
     // optimized away.
     Role::load($role)->revokePermission('administer permissions')->save();
     $element = $test_element;
     $element['#markup'] = 'this should be visible';
     $output = \Drupal::service('renderer')->renderRoot($element);
     $this->assertEqual($output, 'this should be visible');
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     $this->installEntitySchema('user');
     $this->installEntitySchema('comment');
     // Create the anonymous role.
     $this->installConfig(['user']);
     // Create an anonymous user.
     $storage = \Drupal::entityManager()->getStorage('user');
     // Insert a row for the anonymous user.
     $storage->create(array('uid' => 0, 'name' => '', 'status' => 0))->save();
     $admin_role = Role::create(['id' => 'admin', 'permissions' => ['administer comments', 'access user profiles']]);
     $admin_role->save();
     /* @var \Drupal\user\RoleInterface $anonymous_role */
     $anonymous_role = Role::load(Role::ANONYMOUS_ID);
     $anonymous_role->grantPermission('access comments');
     $anonymous_role->save();
     $this->adminUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$admin_role->id()]]);
     $this->adminUser->save();
     // Create some comments.
     $comment = Comment::create(['subject' => 'My comment title', 'uid' => $this->adminUser->id(), 'name' => $this->adminUser->label(), 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'status' => 1]);
     $comment->save();
     $comment_anonymous = Comment::create(['subject' => 'Anonymous comment title', 'uid' => 0, 'name' => 'barry', 'mail' => '*****@*****.**', 'homepage' => 'https://example.com', 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'created' => 123456, 'status' => 1]);
     $comment_anonymous->save();
 }
コード例 #4
0
 public function testRolePurchaseCheckout()
 {
     // Add role assignment to the test product.
     $rid = $this->drupalCreateRole(array('access content'));
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/' . $this->product->id() . '/edit/features', array('feature' => 'role'), t('Add'));
     $edit = array('role' => $rid, 'end_override' => TRUE, 'expire_relative_duration' => 1, 'expire_relative_granularity' => 'day');
     $this->drupalPostForm(NULL, $edit, t('Save feature'));
     // Check out with the test product.
     $method = $this->createPaymentMethod('other');
     $this->addToCart($this->product);
     $order = $this->checkout();
     uc_payment_enter($order->id(), $method['id'], $order->getTotal());
     // Test that the role was granted.
     // @todo Re-enable when Rules is available.
     // $this->assertTrue($order->getOwner()->hasRole($rid), 'Existing user was granted role.');
     // Test that the email is correct.
     $role = Role::load($rid);
     // @todo Re-enable when Rules is available.
     // $this->assertMailString('subject', $role->label(), 4, 'Role assignment email mentions role in subject line.');
     // Test that the role product / user relation is deleted with the user.
     user_delete($order->getOwnerId());
     // Run cron to ensure deleted users are handled correctly.
     $this->cronRun();
 }
コード例 #5
0
 /**
  * Returns the permission strings that a group of roles have.
  *
  * @param array $roleIDs
  *   The array of roleIDs to check.
  * @param bool $groupByRoleId
  *   Choose whether to group permissions by role ID.
  * @return array
  *   An array of the permissions untrusted roles have. If $groupByRoleId is
  *   true, the array key is the role ID, the value is the array of permissions
  *   the role has.
  */
 public static function rolePermissions(array $roleIDs, $groupByRoleId = FALSE)
 {
     // Get the permissions the given roles have, grouped by roles.
     $permissions_grouped = user_role_permissions($roleIDs);
     // Fill up the administrative roles' permissions too.
     foreach ($roleIDs as $roleID) {
         $role = Role::load($roleID);
         /** @var Role $role */
         if ($role->isAdmin()) {
             $permissions_grouped[$roleID] = static::permissions();
         }
     }
     if ($groupByRoleId) {
         // If the result should be grouped, we have nothing else to do.
         return $permissions_grouped;
     } else {
         // Merge the grouped permissions into $untrusted_permissions.
         $untrusted_permissions = array();
         foreach ($permissions_grouped as $rid => $permissions) {
             $untrusted_permissions = array_merge($untrusted_permissions, $permissions);
         }
         // Remove duplicate elements and fix indexes.
         $untrusted_permissions = array_values(array_unique($untrusted_permissions));
         return $untrusted_permissions;
     }
 }
コード例 #6
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to view test entities, so that we can
     // verify the cache tags of cached versions of test entity pages.
     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
     $user_role->grantPermission('view test entity');
     $user_role->save();
     // Create an entity.
     $this->entity = $this->createEntity();
     // If this is an entity with field UI enabled, then add a configurable
     // field. We will use this configurable field in later tests to ensure that
     // field configuration invalidate render cache entries.
     if ($this->entity->getEntityType()->get('field_ui_base_route')) {
         // Add field, so we can modify the field storage and field entities to
         // verify that changes to those indeed clear cache tags.
         entity_create('field_storage_config', array('field_name' => 'configurable_field', 'entity_type' => $this->entity->getEntityTypeId(), 'type' => 'test_field', 'settings' => array()))->save();
         entity_create('field_config', array('entity_type' => $this->entity->getEntityTypeId(), 'bundle' => $this->entity->bundle(), 'field_name' => 'configurable_field', 'label' => 'Configurable field', 'settings' => array()))->save();
         // Reload the entity now that a new field has been added to it.
         $storage = $this->container->get('entity.manager')->getStorage($this->entity->getEntityTypeId());
         $storage->resetCache();
         $this->entity = $storage->load($this->entity->id());
     }
     // Create a referencing and a non-referencing entity.
     list($this->referencingEntity, $this->nonReferencingEntity, ) = $this->createReferenceTestEntities($this->entity);
 }
コード例 #7
0
ファイル: TourCacheTagsTest.php プロジェクト: 318io/318-io
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to view nodes, so that we can verify the
     // cache tags of cached versions of node pages.
     Role::load(RoleInterface::ANONYMOUS_ID)->grantPermission('access tour')->save();
 }
コード例 #8
0
 /**
  * Tests user role migration.
  */
 public function testUserRole()
 {
     /** @var \Drupal\migrate\entity\Migration $migration */
     $id_map = Migration::load('d6_user_role')->getIdMap();
     $rid = 'anonymous';
     $anonymous = Role::load($rid);
     $this->assertIdentical($rid, $anonymous->id());
     $this->assertIdentical(array('migrate test anonymous permission', 'use text format filtered_html'), $anonymous->getPermissions());
     $this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(1)));
     $rid = 'authenticated';
     $authenticated = Role::load($rid);
     $this->assertIdentical($rid, $authenticated->id());
     $this->assertIdentical(array('migrate test authenticated permission', 'use text format filtered_html'), $authenticated->getPermissions());
     $this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(2)));
     $rid = 'migrate_test_role_1';
     $migrate_test_role_1 = Role::load($rid);
     $this->assertIdentical($rid, $migrate_test_role_1->id());
     $this->assertIdentical(array('migrate test role 1 test permission', 'use text format full_html', 'use text format php_code'), $migrate_test_role_1->getPermissions());
     $this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(3)));
     $rid = 'migrate_test_role_2';
     $migrate_test_role_2 = Role::load($rid);
     $this->assertIdentical(array('migrate test role 2 test permission', 'use PHP for settings', 'administer contact forms', 'skip comment approval', 'edit own blog content', 'edit any blog content', 'delete own blog content', 'delete any blog content', 'create forum content', 'delete any forum content', 'delete own forum content', 'edit any forum content', 'edit own forum content', 'administer nodes', 'access content overview', 'use text format php_code'), $migrate_test_role_2->getPermissions());
     $this->assertIdentical($rid, $migrate_test_role_2->id());
     $this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(4)));
     $rid = 'migrate_test_role_3_that_is_long';
     $migrate_test_role_3 = Role::load($rid);
     $this->assertIdentical($rid, $migrate_test_role_3->id());
     $this->assertIdentical(array($rid), $id_map->lookupDestinationId(array(5)));
 }
コード例 #9
0
 /**
  * Helper function to perform assertions on a user role.
  *
  * @param string $id
  *   The role ID.
  * @param string[] $permissions
  *   An array of user permissions.
  * @param int $lookupId
  *   The original numeric ID of the role in the source database.
  * @param \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map
  *   The map table plugin.
  */
 protected function assertRole($id, array $permissions, $lookupId, MigrateIdMapInterface $id_map) {
   /** @var \Drupal\user\RoleInterface $role */
   $role = Role::load($id);
   $this->assertInstanceOf(RoleInterface::class, $role);
   $this->assertSame($permissions, $role->getPermissions());
   $this->assertSame([[$id]], $id_map->lookupDestinationIds(['rid' => $lookupId]));
 }
コード例 #10
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installConfig(array('user', 'entity_test'));
     // Give anonymous users permission to view test entities.
     Role::load(RoleInterface::ANONYMOUS_ID)->grantPermission('view test entity')->save();
 }
コード例 #11
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to access feeds, so that we can verify
     // the cache tags of cached versions of feeds.
     $user_role = Role::load(DRUPAL_ANONYMOUS_RID);
     $user_role->grantPermission('access news feeds');
     $user_role->save();
 }
コード例 #12
0
ファイル: ResourceTest.php プロジェクト: eigentor/tommiblog
 /**
  * Tests that serialization_class is optional.
  */
 public function testSerializationClassIsOptional()
 {
     $this->enableService('serialization_test', 'POST', 'json');
     Role::load(RoleInterface::ANONYMOUS_ID)->grantPermission('restful post serialization_test')->save();
     $serialized = $this->container->get('serializer')->serialize(['foo', 'bar'], 'json');
     $this->httpRequest('serialization_test', 'POST', $serialized, 'application/json');
     $this->assertResponse(200);
     $this->assertResponseBody('["foo","bar"]');
 }
コード例 #13
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to view user profiles, so that we can
     // verify the cache tags of cached versions of user profile pages.
     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
     $user_role->grantPermission('access user profiles');
     $user_role->save();
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     $this->addField('string', 'field_shared', 'user');
     $this->addField('string', 'field_shared', 'simplenews_subscriber');
     Role::load('anonymous')->grantPermission('subscribe to newsletters')->grantPermission('access user profiles')->save();
     Role::load('authenticated')->grantPermission('subscribe to newsletters')->save();
     $this->admin = $this->drupalCreateUser(array('administer users'));
 }
コード例 #15
0
ファイル: ResourceTest.php プロジェクト: Wylbur/gj
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->config = $this->config('rest.settings');
     // Create an entity programmatically.
     $this->entity = $this->entityCreate('entity_test');
     $this->entity->save();
     Role::load(AccountInterface::ANONYMOUS_ROLE)->grantPermission('view test entity')->save();
 }
コード例 #16
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to view nodes, so that we can verify the
     // cache tags of cached versions of node pages.
     $user_role = Role::load(DRUPAL_ANONYMOUS_RID);
     $user_role->grantPermission('acess content');
     $user_role->save();
 }
コード例 #17
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Give anonymous users permission to customize shortcut links, so that we
     // can verify the cache tags of cached versions of shortcuts.
     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
     $user_role->grantPermission('customize shortcut links');
     $user_role->grantPermission('access shortcuts');
     $user_role->save();
 }
コード例 #18
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Remove the 'access content' permission from anonymous and auth users.
     Role::load(RoleInterface::ANONYMOUS_ID)->revokePermission('access content')->save();
     Role::load(RoleInterface::AUTHENTICATED_ID)->revokePermission('access content')->save();
     $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
     $this->drupalCreateContentType(['type' => 'page', 'name' => 'Page']);
     $this->drupalPlaceBlock('page_title_block');
     $this->page = Page::load('node_view');
 }
コード例 #19
0
ファイル: MigrateUserRoleTest.php プロジェクト: 318io/318-io
 /**
  * Asserts aspects of a user role config entity.
  *
  * @param string $id
  *   The role ID.
  * @param string $label
  *   The role's expected label.
  * @param int|NULL $original_rid
  *   The original (integer) ID of the role, to check permissions.
  */
 protected function assertEntity($id, $label, $original_rid)
 {
     /** @var \Drupal\user\RoleInterface $entity */
     $entity = Role::load($id);
     $this->assertTrue($entity instanceof RoleInterface);
     $this->assertIdentical($label, $entity->label());
     if (isset($original_rid)) {
         $permissions = Database::getConnection('default', 'migrate')->select('role_permission', 'rp')->fields('rp', ['permission'])->condition('rid', $original_rid)->execute()->fetchCol();
         $this->assertIdentical($permissions, $entity->getPermissions());
     }
 }
コード例 #20
0
/**
 * Explain your records in the {node_access} table.
 *
 * In order to help developers and administrators understand the forces
 * that control access to any given node, the DNA module provides the
 * Devel Node Access block, which lists all the grant records in the
 * {node_access} table for that node.
 *
 * However, every Node Access module is free in how it defines and uses the
 * 'realm' and 'gid' fields in its records in the {node_access} table, and
 * it's often difficult to interpret them. This hook passes each record
 * that DNA wants to display, and the owning module is expected to return
 * an explanation of that record.
 *
 * The explanation should not be localized (not be passed through t()), so
 * that administrators seeking help can present English explanations.
 *
 * @param $row
 *   The record from the {node_access} table, as object. The member fields are:
 *   nid, gid, realm, grant_view, grant_update, grant_delete.
 *
 * @return string|null
 *   A string with a (short!) explanation of the given {node_access} row,
 *   to be displayed in DNA's 'Devel Node Access' block. It will be displayed
 *   as HTML; any variable parts must already be sanitized.
 *
 * @see hook_node_access_records()
 * @see devel_node_access_node_access_explain()
 *
 * @ingroup node_access
 */
function hook_node_access_explain($row)
{
    if ($row->realm == 'mymodule_myrealm') {
        if ($row->grant_view) {
            /** @var \Drupal\user\RoleInterface $role */
            $role = \Drupal\user\Entity\Role::load($row->gid);
            return t('Role %role may view this node.', array('%role' => $role->get('name')));
        } else {
            return 'No access.';
        }
    }
    return null;
}
コード例 #21
0
 /**
  * {@inheritdoc}
  */
 protected function setUpFixtures()
 {
     parent::setUpFixtures();
     $this->installEntitySchema('user');
     $this->installEntitySchema('entity_test');
     $this->installConfig(['user']);
     // Create some test entities.
     for ($i = 0; $i < 5; $i++) {
         EntityTest::create(['name' => $this->randomString()])->save();
     }
     // Create and admin user.
     $this->adminUser = $this->createUser(['view test entity'], FALSE, TRUE);
     Role::load(AccountInterface::ANONYMOUS_ROLE)->grantPermission('view test entity')->save();
 }
コード例 #22
0
 /**
  * Tests Standard installation profile.
  */
 public function testCasAutoAssignedRoles()
 {
     $role_id = $this->drupalCreateRole([]);
     $role_id_2 = $this->drupalCreateRole([]);
     $edit = ['user_accounts[auto_register]' => TRUE, 'user_accounts[auto_assigned_roles_enable]' => TRUE, 'user_accounts[auto_assigned_roles][]' => [$role_id, $role_id_2]];
     $this->drupalPostForm('/admin/config/people/cas', $edit, 'Save configuration');
     $this->assertEquals([$role_id, $role_id_2], $this->config('cas.settings')->get('user_accounts.auto_assigned_roles'));
     $cas_property_bag = new CasPropertyBag('test_cas_user_name');
     \Drupal::service('cas.login')->loginToDrupal($cas_property_bag, 'fake_ticket_string');
     $user = user_load_by_name('test_cas_user_name');
     $this->assertTrue($user->hasRole($role_id), 'The user has the auto assigned role: ' . $role_id);
     $this->assertTrue($user->hasRole($role_id_2), 'The user has the auto assigned role: ' . $role_id_2);
     Role::load($role_id_2)->delete();
     $this->assertEquals([$role_id], $this->config('cas.settings')->get('user_accounts.auto_assigned_roles'));
 }
コード例 #23
0
ファイル: UserRoleAdminTest.php プロジェクト: aWEBoLabs/taxi
 /**
  * Test adding, renaming and deleting roles.
  */
 function testRoleAdministration()
 {
     $this->drupalLogin($this->adminUser);
     $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
     // Test presence of tab.
     $this->drupalGet('admin/people/permissions');
     $tabs = $this->xpath('//ul[@class=:classes and //a[contains(., :text)]]', array(':classes' => 'tabs primary', ':text' => t('Roles')));
     $this->assertEqual(count($tabs), 1, 'Found roles tab');
     // Test adding a role. (In doing so, we use a role name that happens to
     // correspond to an integer, to test that the role administration pages
     // correctly distinguish between role names and IDs.)
     $role_name = '123';
     $edit = array('label' => $role_name, 'id' => $role_name);
     $this->drupalPostForm('admin/people/roles/add', $edit, t('Save'));
     $this->assertRaw(t('Role %label has been added.', array('%label' => 123)));
     $role = Role::load($role_name);
     $this->assertTrue(is_object($role), 'The role was successfully retrieved from the database.');
     // Check that the role was created in site default language.
     $this->assertEqual($role->language()->getId(), $default_langcode);
     // Try adding a duplicate role.
     $this->drupalPostForm('admin/people/roles/add', $edit, t('Save'));
     $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'), 'Duplicate role warning displayed.');
     // Test renaming a role.
     $role_name = '456';
     $edit = array('label' => $role_name);
     $this->drupalPostForm("admin/people/roles/manage/{$role->id()}", $edit, t('Save'));
     $this->assertRaw(t('Role %label has been updated.', array('%label' => $role_name)));
     \Drupal::entityManager()->getStorage('user_role')->resetCache(array($role->id()));
     $new_role = Role::load($role->id());
     $this->assertEqual($new_role->label(), $role_name, 'The role name has been successfully changed.');
     // Test deleting a role.
     $this->drupalGet("admin/people/roles/manage/{$role->id()}");
     $this->clickLink(t('Delete'));
     $this->drupalPostForm(NULL, array(), t('Delete'));
     $this->assertRaw(t('The role %label has been deleted.', array('%label' => $role_name)));
     $this->assertNoLinkByHref("admin/people/roles/manage/{$role->id()}", 'Role edit link removed.');
     \Drupal::entityManager()->getStorage('user_role')->resetCache(array($role->id()));
     $this->assertFalse(Role::load($role->id()), 'A deleted role can no longer be loaded.');
     // Make sure that the system-defined roles can be edited via the user
     // interface.
     $this->drupalGet('admin/people/roles/manage/' . RoleInterface::ANONYMOUS_ID);
     $this->assertResponse(200, 'Access granted when trying to edit the built-in anonymous role.');
     $this->assertNoText(t('Delete role'), 'Delete button for the anonymous role is not present.');
     $this->drupalGet('admin/people/roles/manage/' . RoleInterface::AUTHENTICATED_ID);
     $this->assertResponse(200, 'Access granted when trying to edit the built-in authenticated role.');
     $this->assertNoText(t('Delete role'), 'Delete button for the authenticated role is not present.');
 }
コード例 #24
0
 /**
  * Tests the editor file reference filter with private files.
  */
 function testEditorPrivateFileReferenceFilter()
 {
     $author = $this->drupalCreateUser();
     $this->drupalLogin($author);
     // Create a content type with a body field.
     $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
     // Create a file in the 'private:// ' stream.
     $filename = 'test.png';
     $src = '/system/files/' . $filename;
     /** @var \Drupal\file\FileInterface $file */
     $file = File::create(['uri' => 'private://' . $filename]);
     $file->setTemporary();
     $file->setOwner($author);
     // Create the file itself.
     file_put_contents($file->getFileUri(), $this->randomString());
     $file->save();
     // The image should be visible for its author.
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(200);
     // The not-yet-permanent image should NOT be visible for anonymous.
     $this->drupalLogout();
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(403);
     // Resave the file to be permanent.
     $file->setPermanent();
     $file->save();
     // Create a node with its body field properly pointing to the just-created
     // file.
     $node = $this->drupalCreateNode(['type' => 'page', 'body' => ['value' => '<img alt="alt" data-entity-type="file" data-entity-uuid="' . $file->uuid() . '" src="' . $src . '" />', 'format' => 'private_images'], 'uid' => $author->id()]);
     // Do the actual test. The image should be visible for anonymous users,
     // because they can view the referencing entity.
     $this->drupalGet($node->toUrl());
     $this->assertSession()->statusCodeEquals(200);
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(200);
     // Disallow anonymous users to view the entity, which then should also
     // disallow them to view the image.
     Role::load(RoleInterface::ANONYMOUS_ID)->revokePermission('access content')->save();
     $this->drupalGet($node->toUrl());
     $this->assertSession()->statusCodeEquals(403);
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(403);
 }
コード例 #25
0
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('entity_test_rev');
     // Give anonymous users permission to view test entities.
     $this->installConfig(array('user'));
     Role::load(RoleInterface::ANONYMOUS_ID)->grantPermission('view test entity')->save();
     $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType);
     // Add the mapping.
     $mapping = rdf_get_mapping('entity_test', 'entity_test');
     $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:knows')))->save();
     // Create the entity to be referenced.
     $this->targetEntity = entity_create($this->entityType, array('name' => $this->randomMachineName()));
     $this->targetEntity->save();
     // Create the entity that will have the entity reference field.
     $this->entity = entity_create($this->entityType, array('name' => $this->randomMachineName()));
     $this->entity->save();
     $this->entity->{$this->fieldName}->entity = $this->targetEntity;
     $this->uri = $this->getAbsoluteUri($this->entity);
 }
コード例 #26
0
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     ViewTestData::createTestViews(get_class($this), ['comment_test_views']);
     $this->installEntitySchema('user');
     $this->installEntitySchema('comment');
     $this->installConfig(['user']);
     $entity_manager = $this->container->get('entity.manager');
     $this->commentStorage = $entity_manager->getStorage('comment');
     $this->userStorage = $entity_manager->getStorage('user');
     // Insert a row for the anonymous user.
     $this->userStorage->create(['uid' => 0, 'name' => '', 'status' => 0])->save();
     $admin_role = Role::create(['id' => 'admin']);
     $admin_role->grantPermission('administer comments');
     $admin_role->save();
     /* @var \Drupal\user\RoleInterface $anonymous_role */
     $anonymous_role = Role::load(Role::ANONYMOUS_ID);
     $anonymous_role->grantPermission('access comments');
     $anonymous_role->save();
     $this->adminUser = $this->userStorage->create(['name' => $this->randomMachineName()]);
     $this->adminUser->addRole('admin');
     $this->adminUser->save();
 }
コード例 #27
0
 /**
  * Tests that the taxonomy term view is working properly.
  */
 public function testTaxonomyTermView()
 {
     // Create terms in the vocabulary.
     $term = $this->createTerm($this->vocabulary);
     // Post an article.
     $edit = array();
     $edit['title[0][value]'] = $original_title = $this->randomMachineName();
     $edit['body[0][value]'] = $this->randomMachineName();
     $edit["{$this->field_name_1}[]"] = $term->id();
     $this->drupalPostForm('node/add/article', $edit, t('Save'));
     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
     $this->drupalGet('taxonomy/term/' . $term->id());
     $this->assertText($term->label());
     $this->assertText($node->label());
     \Drupal::moduleHandler()->install(array('language', 'content_translation'));
     $language = ConfigurableLanguage::createFromLangcode('ur');
     $language->save();
     // Enable translation for the article content type and ensure the change is
     // picked up.
     content_translation_set_config('node', 'article', 'enabled', TRUE);
     $roles = $this->admin_user->getRoles(TRUE);
     Role::load(reset($roles))->grantPermission('create content translations')->grantPermission('translate any entity')->save();
     drupal_static_reset();
     \Drupal::entityManager()->clearCachedDefinitions();
     \Drupal::service('router.builder')->rebuild();
     $edit['title[0][value]'] = $translated_title = $this->randomMachineName();
     $this->drupalPostForm('node/' . $node->id() . '/translations/add/en/ur', $edit, t('Save (this translation)'));
     $this->drupalGet('taxonomy/term/' . $term->id());
     $this->assertText($term->label());
     $this->assertText($original_title);
     $this->assertNoText($translated_title);
     $this->drupalGet('ur/taxonomy/term/' . $term->id());
     $this->assertText($term->label());
     $this->assertNoText($original_title);
     $this->assertText($translated_title);
 }
コード例 #28
0
 /**
  * Tests support for different cache items with different request formats
  * specified via a query parameter.
  */
 function testQueryParameterFormatRequests()
 {
     $config = $this->config('system.performance');
     $config->set('cache.page.max_age', 300);
     $config->save();
     $accept_header_cache_url = Url::fromRoute('system_test.page_cache_accept_header');
     $accept_header_cache_url_with_json = Url::fromRoute('system_test.page_cache_accept_header', ['_format' => 'json']);
     $this->drupalGet($accept_header_cache_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'HTML page was not yet cached.');
     $this->drupalGet($accept_header_cache_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'HTML page was cached.');
     $this->assertRaw('<p>oh hai this is html.</p>', 'The correct HTML response was returned.');
     $this->drupalGet($accept_header_cache_url_with_json);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Json response was not yet cached.');
     $this->drupalGet($accept_header_cache_url_with_json);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Json response was cached.');
     $this->assertRaw('{"content":"oh hai this is json"}', 'The correct Json response was returned.');
     // Enable REST support for nodes and hal+json.
     \Drupal::service('module_installer')->install(['node', 'rest', 'hal']);
     $this->drupalCreateContentType(['type' => 'article']);
     $node = $this->drupalCreateNode(['type' => 'article']);
     $node_uri = $node->urlInfo();
     $node_url_with_hal_json_format = $node->urlInfo('canonical')->setRouteParameter('_format', 'hal_json');
     /** @var \Drupal\user\RoleInterface $role */
     $role = Role::load('anonymous');
     $role->grantPermission('restful get entity:node');
     $role->save();
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     // Now request a HAL page, we expect that the first request is a cache miss
     // and it serves HTML.
     $this->drupalGet($node_url_with_hal_json_format);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_url_with_hal_json_format);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     // Clear the page cache. After that request a HAL request, followed by an
     // ordinary HTML one.
     \Drupal::cache('render')->deleteAll();
     $this->drupalGet($node_url_with_hal_json_format);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_url_with_hal_json_format);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
 }
コード例 #29
0
ファイル: UserCreationTrait.php プロジェクト: aWEBoLabs/taxi
 /**
  * Creates a role with specified permissions.
  *
  * @param array $permissions
  *   Array of permission names to assign to role.
  * @param string $rid
  *   (optional) The role ID (machine name). Defaults to a random name.
  * @param string $name
  *   (optional) The label for the role. Defaults to a random string.
  * @param int $weight
  *   (optional) The weight for the role. Defaults NULL so that entity_create()
  *   sets the weight to maximum + 1.
  *
  * @return string
  *   Role ID of newly created role, or FALSE if role creation failed.
  */
 protected function createRole(array $permissions, $rid = NULL, $name = NULL, $weight = NULL)
 {
     // Generate a random, lowercase machine name if none was passed.
     if (!isset($rid)) {
         $rid = strtolower($this->randomMachineName(8));
     }
     // Generate a random label.
     if (!isset($name)) {
         // In the role UI role names are trimmed and random string can start or
         // end with a space.
         $name = trim($this->randomString(8));
     }
     // Check the all the permissions strings are valid.
     if (!$this->checkPermissions($permissions)) {
         return FALSE;
     }
     // Create new role.
     $role = Role::create(array('id' => $rid, 'label' => $name));
     if (isset($weight)) {
         $role->set('weight', $weight);
     }
     $result = $role->save();
     $this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array('@name' => var_export($role->label(), TRUE), '@rid' => var_export($role->id(), TRUE))), 'Role');
     if ($result === SAVED_NEW) {
         // Grant the specified permissions to the role, if any.
         if (!empty($permissions)) {
             $this->grantPermissions($role, $permissions);
             $assigned_permissions = Role::load($role->id())->getPermissions();
             $missing_permissions = array_diff($permissions, $assigned_permissions);
             if (!$missing_permissions) {
                 $this->pass(SafeMarkup::format('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), 'Role');
             } else {
                 $this->fail(SafeMarkup::format('Failed to create permissions: @perms', array('@perms' => implode(', ', $missing_permissions))), 'Role');
             }
         }
         return $role->id();
     } else {
         return FALSE;
     }
 }
コード例 #30
0
 /**
  * Assert inaccessible items don't change the data of the fields.
  */
 public function testAccess()
 {
     // Revoke the 'view test entity' permission for this test.
     Role::load(RoleInterface::ANONYMOUS_ID)->revokePermission('view test entity')->save();
     $field_name = $this->fieldName;
     $referencing_entity = $this->container->get('entity_type.manager')->getStorage($this->entityType)->create(array('name' => $this->randomMachineName()));
     $referencing_entity->save();
     $referencing_entity->{$field_name}->entity = $this->referencedEntity;
     // Assert user doesn't have access to the entity.
     $this->assertFalse($this->referencedEntity->access('view'), 'Current user does not have access to view the referenced entity.');
     $formatter_manager = $this->container->get('plugin.manager.field.formatter');
     // Get all the existing formatters.
     foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) {
         // Set formatter type for the 'full' view mode.
         entity_get_display($this->entityType, $this->bundle, 'default')->setComponent($field_name, array('type' => $formatter))->save();
         // Invoke entity view.
         entity_view($referencing_entity, 'default');
         // Verify the un-accessible item still exists.
         $this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', array('@name' => $name)));
     }
 }