You are here

class OAuthKeyForm in Lightning API 8

Same name and namespace in other branches
  1. 8.4 src/Form/OAuthKeyForm.php \Drupal\lightning_api\Form\OAuthKeyForm
  2. 8.2 src/Form/OAuthKeyForm.php \Drupal\lightning_api\Form\OAuthKeyForm
  3. 8.3 src/Form/OAuthKeyForm.php \Drupal\lightning_api\Form\OAuthKeyForm

Hierarchy

Expanded class hierarchy of OAuthKeyForm

1 file declares its use of OAuthKeyForm
OAuthKeyFormTest.php in tests/src/Kernel/OAuthKeyFormTest.php
1 string reference to 'OAuthKeyForm'
lightning_api.routing.yml in ./lightning_api.routing.yml
lightning_api.routing.yml

File

src/Form/OAuthKeyForm.php, line 13

Namespace

Drupal\lightning_api\Form
View source
class OAuthKeyForm extends ConfigFormBase {

  /**
   * The OAuth key service.
   *
   * @var \Drupal\lightning_api\OAuthKey
   */
  protected $key;

  /**
   * OAuthKeyForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\lightning_api\OAuthKey $key
   *   The OAuth keys service.
   * @param TranslationInterface $translation
   *   The string translation service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, OAuthKey $key, TranslationInterface $translation) {
    parent::__construct($config_factory);
    $this->key = $key;
    $this
      ->setStringTranslation($translation);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('lightning_api.oauth_key'), $container
      ->get('string_translation'));
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'simple_oauth.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'oauth_key_form';
  }

  /**
   * Handles exceptions caught during form submission.
   *
   * @param \Exception $e
   *   The caught exception.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   */
  private function onException(\Exception $e, FormStateInterface $form_state) {
    drupal_set_message($e
      ->getMessage(), 'error');
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (extension_loaded('openssl') == FALSE) {
      drupal_set_message($this
        ->t('The OpenSSL extension is unavailable. Please enable it to generate OAuth keys.'), 'error');
      return $form;
    }
    if ($this->key
      ->exists() && $form_state
      ->isSubmitted() == FALSE && $form_state
      ->isRebuilding() == FALSE) {
      drupal_set_message($this
        ->t('A key pair already exists and will be overwritten if you generate new keys.'), 'warning');
    }
    $form['dir'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Destination'),
      '#description' => $this
        ->t('Path to the directory in which to store the generated keys.'),
      '#required' => TRUE,
      '#element_validate' => [
        '::validateDestinationExists',
      ],
    ];
    $form['advanced'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Advanced'),
    ];
    $form['advanced']['private_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Private key name'),
      '#description' => $this
        ->t('File name of the generated private key. Will be automatically generated if left empty.'),
      '#element_validate' => [
        '::validateKeyFileName',
      ],
    ];
    $form['advanced']['public_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Public key name'),
      '#description' => $this
        ->t('File name of the generated public key. Will be automatically generated if left empty.'),
      '#element_validate' => [
        '::validateKeyFileName',
      ],
    ];
    $form['advanced']['conf'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('OpenSSL configuration file'),
      '#description' => $this
        ->t('Path to the openssl.cnf configuration file. PHP will attempt to auto-detect this if not specified.'),
    ];
    $form['generate'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Generate keys'),
    ];
    return $form;
  }

  /**
   * Ensures that the destination directory exists.
   *
   * @param array $element
   *   The form element being validated.
   * @param FormStateInterface $form_state
   *   The current form state.
   */
  public function validateDestinationExists(array &$element, FormStateInterface $form_state) {
    $dir = $element['#value'];
    if (is_dir($dir) == FALSE) {
      $form_state
        ->setError($element, $this
        ->t('%dir does not exist.', [
        '%dir' => $dir,
      ]));
    }
  }

  /**
   * Ensures that a requested file name contains no illegal characters.
   *
   * @param array $element
   *   The form element being validated.
   * @param FormStateInterface $form_state
   *   The current form state.
   */
  public function validateKeyFileName(array &$element, FormStateInterface $form_state) {
    $value = $element['#value'];
    if (strpos($value, '/') !== FALSE) {
      $form_state
        ->setError($element, $this
        ->t('%value is not a valid name for a key file.', [
        '%value' => $value,
      ]));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $conf = [];

    // Gather OpenSSL configuration values specified by the user.
    $config = $form_state
      ->getValue('conf');
    if ($config) {
      $conf['config'] = $config;
    }
    try {
      list($private_key, $public_key) = OAuthKey::generate($conf);
    } catch (KeyGenerationException $e) {
      return $this
        ->onException($e, $form_state);
    }
    $dir = rtrim($form_state
      ->getValue('dir'), '/');
    $config = $this
      ->config('simple_oauth.settings');
    try {
      $destination = $dir . '/' . trim($form_state
        ->getValue('private_key'));
      $destination = $this->key
        ->write($destination, $private_key);
      $config
        ->set('private_key', $destination);
      $destination = $dir . '/' . trim($form_state
        ->getValue('public_key'));
      $destination = $this->key
        ->write($destination, $public_key);
      $config
        ->set('public_key', $destination);
      $config
        ->save();
    } catch (\RuntimeException $e) {
      return $this
        ->onException($e, $form_state);
    }
    drupal_set_message($this
      ->t('A key pair was generated successfully.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OAuthKeyForm::$key protected property The OAuth key service.
OAuthKeyForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
OAuthKeyForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
OAuthKeyForm::getEditableConfigNames public function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
OAuthKeyForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OAuthKeyForm::onException private function Handles exceptions caught during form submission.
OAuthKeyForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
OAuthKeyForm::validateDestinationExists public function Ensures that the destination directory exists.
OAuthKeyForm::validateKeyFileName public function Ensures that a requested file name contains no illegal characters.
OAuthKeyForm::__construct public function OAuthKeyForm constructor. Overrides ConfigFormBase::__construct
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.