You are here

function _oauth2_client_test_create in OAuth2 Client 8

Same name and namespace in other branches
  1. 7.2 tests/oauth2_client_test.install \_oauth2_client_test_create()
  2. 7 tests/oauth2_client_test.install \_oauth2_client_test_create()

Create a test server, along with test clients and scopes.

1 call to _oauth2_client_test_create()
oauth2_client_test_enable in tests/oauth2_client_test/oauth2_client_test.install
Implements hook_enable().

File

tests/oauth2_client_test/oauth2_client_test.install, line 22
Enable and disable hook functions.

Code

function _oauth2_client_test_create() {
  $serverStorage = \Drupal::entityTypeManager()
    ->getStorage('oauth2_server');

  // Create the server and client.
  $server = $serverStorage
    ->create();
  $server->name = 'test_oauth2_server';
  $server->label = 'Test';
  $server->settings = [
    'default_scope' => 'scope1',
    'enforce_state' => TRUE,
    'allow_implicit' => TRUE,
    'require_exact_redirect_uri' => FALSE,
    'grant_types' => [
      'authorization_code' => 'authorization_code',
      'client_credentials' => 'client_credentials',
      'refresh_token' => 'refresh_token',
      'password' => 'password',
    ],
    'always_issue_new_refresh_token' => TRUE,
    // For testing purposes, set short expire times.
    'access_lifetime' => 20,
    'refresh_token_lifetime' => 30,
  ];
  $server
    ->save();
  $serverClientStorage = \Drupal::entityTypeManager()
    ->getStorage('oauth2_server_client');

  // Add a client.
  $client = $serverClientStorage
    ->create();
  $client->server = $server->name;
  $client->label = 'Client 1';
  $client->client_key = 'client1';
  $client->client_secret = 'secret1';
  $client->redirect_uri = Url::fromUserInput('oauth2/authorized', [
    'absolute' => TRUE,
  ])
    ->toString();
  $client->automatic_authorization = FALSE;
  $client
    ->save();

  // The second client has automatic_authorization TRUE.
  $client = $serverClientStorage
    ->create();
  $client->server = $server->name;
  $client->label = 'Client 2';
  $client->client_key = 'client2';
  $client->client_secret = 'secret2';
  $client->redirect_uri = Url::fromUserInput('oauth2/authorized', [
    'absolute' => TRUE,
  ])
    ->toString();
  $client->automatic_authorization = TRUE;
  $client
    ->save();

  // Creates some scopes.
  $scopes = [
    'scope1' => 'Scope 1',
    'scope2' => 'Scope 2',
  ];
  $serverScopeStorage = \Drupal::entityTypeManager()
    ->getStorage('oauth2_server_scope');
  foreach ($scopes as $scope_name => $scope_label) {
    $scope = $serverScopeStorage
      ->create();
    $scope->server = $server->name;
    $scope->name = $scope_name;
    $scope->description = $scope_label;
    $scope
      ->save();
  }

  // Create a test user.
  \Drupal::entityTypeManager()
    ->getStorage('user')
    ->create([
    'name' => 'user1',
    'pass' => 'pass1',
    'status' => 1,
  ])
    ->save();
}