You are here

public function ConsumerConfigTest::testLimitUserAccess in farmOS 2.x

Test consumer.limit_user_access.

File

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

Class

ConsumerConfigTest
Tests using the consumer.client_id field.

Namespace

Drupal\Tests\farm_api\Functional

Code

public function testLimitUserAccess() {

  // 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 one additional role.
  $this->user
    ->addRole('scope_1');
  $this->user
    ->save();

  // Grant the client all roles.
  $client_roles = array_merge($this
    ->getClientRoleIds(), [
    'scope_1',
    'scope_2',
    'scope_3',
  ]);
  $this
    ->grantClientRoles($client_roles);

  // Array of expected roles. Includes all roles the consumer has.
  $expected_roles = array_merge($client_roles, [
    'authenticated',
  ]);

  // 1. Test that all roles on the consumer are granted.
  $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 only the roles the user has are granted.
  // Update the client.
  $this->client
    ->set('limit_user_access', TRUE);
  $this->client
    ->save();
  $requested_roles = [
    'scope_1',
    'scope_3',
  ];
  $expected_roles = [
    'scope_1',
    'authenticated',
  ];

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

  // 3. Test that limit_user_access and grant_user_access work together.
  $this->client
    ->set('grant_user_access', TRUE);
  $this->client
    ->set('limit_user_access', TRUE);
  $this->client
    ->save();
  $requested_roles = [];
  $expected_roles = [
    'scope_1',
    'authenticated',
  ];

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