You are here

public function Oauth2ClientPluginConfigForm::testToken in OAuth2 Client 8.3

Additional submit function for saving both config and token.

Parameters

array $form: The current form build.

\Drupal\Core\Form\FormStateInterface $formState: The current form state object.

File

src/Form/Oauth2ClientPluginConfigForm.php, line 130

Class

Oauth2ClientPluginConfigForm
Configure OAuth2 Client settings for this site.

Namespace

Drupal\oauth2_client\Form

Code

public function testToken(array &$form, FormStateInterface $formState) {
  $this
    ->submitForm($form, $formState);

  // Try to obtain a token.
  try {

    // Clear the existing token.
    $this->clientService
      ->clearAccessToken($this->plugin
      ->getId());
    $values = $formState
      ->getValues();
    $provider = $values['plugin']['credential_provider'];
    $credentials = $values['plugin'][$provider];
    $user = $credentials['username'] ?? NULL;
    $password = $credentials['password'] ?? NULL;
    $token = $this->clientService
      ->getAccessToken($this->plugin
      ->getId(), $user, $password);
    if ($token instanceof AccessTokenInterface) {
      $formState
        ->setRedirect('oauth2_client.oauth2_client_plugin_list');
    }
  } catch (\Exception $e) {
    $formState
      ->disableRedirect();

    // Failed to get the access token.
    $this->messenger
      ->addError($this
      ->t('Unable to obtain an OAuth token. The error message is: @message', [
      '@message' => $e
        ->getMessage(),
    ]));
    watchdog_exception('Oauth2 Client', $e);
  }
}