You are here

public function NodeQueryAlterTest::testNodeQueryAlterOverride in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/node/tests/src/Functional/NodeQueryAlterTest.php \Drupal\Tests\node\Functional\NodeQueryAlterTest::testNodeQueryAlterOverride()

Tests 'node_access' query alter override.

Verifies that node_access_view_all_nodes() is called from node_query_node_access_alter(). We do this by checking that a user who normally would not have view privileges is able to view the nodes when we add a record to {node_access} paired with a corresponding privilege in hook_node_grants().

File

core/modules/node/tests/src/Functional/NodeQueryAlterTest.php, line 163

Class

NodeQueryAlterTest
Tests that node access queries are properly altered by the node module.

Namespace

Drupal\Tests\node\Functional

Code

public function testNodeQueryAlterOverride() {
  $record = [
    'nid' => 0,
    'gid' => 0,
    'realm' => 'node_access_all',
    'grant_view' => 1,
    'grant_update' => 0,
    'grant_delete' => 0,
  ];
  $connection = Database::getConnection();
  $connection
    ->insert('node_access')
    ->fields($record)
    ->execute();

  // Test that the noAccessUser still doesn't have the 'view'
  // privilege after adding the node_access record.
  drupal_static_reset('node_access_view_all_nodes');
  try {
    $query = $connection
      ->select('node', 'n')
      ->fields('n');
    $query
      ->addTag('node_access');
    $query
      ->addMetaData('op', 'view');
    $query
      ->addMetaData('account', $this->noAccessUser);
    $result = $query
      ->execute()
      ->fetchAll();
    $this
      ->assertCount(0, $result, 'User view privileges are not overridden');
  } catch (\Exception $e) {
    $this
      ->fail('Altered query is malformed');
  }

  // Have node_test_node_grants return a node_access_all privilege,
  // to grant the noAccessUser 'view' access.  To verify that
  // node_access_view_all_nodes is properly checking the specified
  // $account instead of the current user, we will log in as
  // noAccessUser2.
  $this
    ->drupalLogin($this->noAccessUser2);
  \Drupal::state()
    ->set('node_access_test.no_access_uid', $this->noAccessUser
    ->id());
  drupal_static_reset('node_access_view_all_nodes');
  try {
    $query = $connection
      ->select('node', 'n')
      ->fields('n');
    $query
      ->addTag('node_access');
    $query
      ->addMetaData('op', 'view');
    $query
      ->addMetaData('account', $this->noAccessUser);
    $result = $query
      ->execute()
      ->fetchAll();
    $this
      ->assertCount(4, $result, 'User view privileges are overridden');
  } catch (\Exception $e) {
    $this
      ->fail('Altered query is malformed');
  }
  \Drupal::state()
    ->delete('node_access_test.no_access_uid');
}