You are here

public function ConsumerConfigTest::testGrantUserAccess in farmOS 2.x

Test consumer.grant_user_access config.

File

modules/core/api/tests/src/Functional/ConsumerConfigTest.php, line 48

Class

ConsumerConfigTest
Tests using the consumer.client_id field.

Namespace

Drupal\Tests\farm_api\Functional

Code

public function testGrantUserAccess() {

  // Set up the client.
  $this->client
    ->set('grant_user_access', FALSE);
  $this->client
    ->set('limit_requested_access', FALSE);
  $this->client
    ->set('limit_user_access', FALSE);
  $this->client
    ->save();

  // Grant the user more roles than the consumer.
  $this->user
    ->addRole('scope_1');
  $this->user
    ->addRole('scope_2');
  $this->user
    ->save();

  // 1. Test that only the consumers roles are granted.
  // Prepare expected roles. Include all roles the consumer has.
  $expected_roles = array_merge($this
    ->getClientRoleIds(), [
    'authenticated',
  ]);

  // Check the token.
  $access_token = $this
    ->getAccessToken();
  $token_info = $this
    ->getTokenInfo($access_token);
  $this
    ->assertEquals($this->user
    ->id(), $token_info['id']);
  $this
    ->assertEqualsCanonicalizing($expected_roles, $token_info['roles']);

  // 2. Test that the user's roles are granted as well.
  // Update the client.
  $this->client
    ->set('grant_user_access', TRUE);
  $this->client
    ->save();

  // Include the consumer + user roles.
  $expected_roles = array_merge($expected_roles, [
    'scope_1',
    'scope_2',
  ]);

  // Check the token.
  $access_token = $this
    ->getAccessToken();
  $token_info = $this
    ->getTokenInfo($access_token);
  $this
    ->assertEquals($this->user
    ->id(), $token_info['id']);
  $this
    ->assertEqualsCanonicalizing($expected_roles, $token_info['roles']);

  // 3. Test that additional roles are not granted.
  // Request "scope_3" even though it is not given to the user or consumer.
  // Check the token.
  $access_token = $this
    ->getAccessToken([
    'scope_3',
  ]);
  $token_info = $this
    ->getTokenInfo($access_token);
  $this
    ->assertEquals($this->user
    ->id(), $token_info['id']);
  $this
    ->assertEqualsCanonicalizing($expected_roles, $token_info['roles']);
}