You are here

class Oauth2GenerateKeyForm in Simple OAuth (OAuth2) & OpenID Connect 8.4

Same name and namespace in other branches
  1. 8.3 src/Entity/Form/Oauth2GenerateKeyForm.php \Drupal\simple_oauth\Entity\Form\Oauth2GenerateKeyForm
  2. 5.x src/Entity/Form/Oauth2GenerateKeyForm.php \Drupal\simple_oauth\Entity\Form\Oauth2GenerateKeyForm

@internal

Hierarchy

Expanded class hierarchy of Oauth2GenerateKeyForm

1 file declares its use of Oauth2GenerateKeyForm
Oauth2GenerateKey.php in src/Controller/Oauth2GenerateKey.php

File

src/Entity/Form/Oauth2GenerateKeyForm.php, line 17

Namespace

Drupal\simple_oauth\Entity\Form
View source
class Oauth2GenerateKeyForm extends FormBase {

  /**
   * @var \Drupal\simple_oauth\Service\KeyGeneratorService
   */
  private $keyGen;

  /**
   * Oauth2GenerateKeyForm constructor.
   *
   * @param \Drupal\simple_oauth\Service\KeyGeneratorService $key_generator_service
   */
  public function __construct(KeyGeneratorService $key_generator_service) {
    $this->keyGen = $key_generator_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('simple_oauth.key.generator'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $pubk_id = NULL, $pk_id = NULL) {

    // Hidden public key id.
    $form['key_settings']['pubk_id'] = [
      '#type' => 'hidden',
      '#required' => TRUE,
      '#value' => $pubk_id,
    ];

    // Hidden private key id.
    $form['key_settings']['pk_id'] = [
      '#type' => 'hidden',
      '#required' => TRUE,
      '#value' => $pk_id,
    ];

    // Error Messages container.
    $form['key_settings']['message'] = [
      '#markup' => '<div id="key-error-message" class="messages messages--error"></div>',
      '#hidden' => TRUE,
    ];
    $disclaimer = '<p>' . $this
      ->t('This is the directory where the public and private keys will be stored after generation. This <strong>SHOULD</strong> be located outside of your webroot to avoid making them public unintentionally.') . '</p><p>' . $this
      ->t('Any keys already present in this directory will be deleted.') . '</p>';

    // Private Key Path.
    $form['key_settings']['directory'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Directory for the keys'),
      '#description' => $disclaimer,
      '#required' => TRUE,
      '#attributes' => [
        'id' => "dir_path",
      ],
    ];

    // Submit.
    $form['key_settings']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Generate'),
      '#ajax' => [
        'callback' => '::generateKeys',
        'event' => 'click',
      ],
    ];
    return $form;
  }

  /**
   * Generate public and private keys.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function generateKeys(&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Get all the values.
    $values = $form_state
      ->getValues();

    // Get Private key path.
    $dir_path = $values['directory'];
    if (!isset($dir_path)) {
      $response
        ->addCommand(new InvokeCommand('#key-error-message', 'show'));
      return $response
        ->addCommand(new HtmlCommand('#key-error-message', $this
        ->t('The directory is required.')));
    }
    try {

      // Generate keys.
      $this->keyGen
        ->generateKeys($dir_path);
    } catch (\Exception $exception) {

      // If exception log it and return an error message.
      watchdog_exception('simple_oauth', $exception);
      $response
        ->addCommand(new InvokeCommand('#key-error-message', 'show'));
      return $response
        ->addCommand(new HtmlCommand('#key-error-message', $exception
        ->getMessage()));
    }

    // Close dialog.
    $response
      ->addCommand(new CloseDialogCommand());

    // Update private key field if id was supplied on the build form.
    if (isset($values['pk_id'])) {
      $response
        ->addCommand(new InvokeCommand('#' . $values['pk_id'], 'val', [
        $dir_path . '/private.key',
      ]));
    }
    if (isset($values['pubk_id'])) {
      $response
        ->addCommand(new InvokeCommand('#' . $values['pubk_id'], 'val', [
        $dir_path . '/public.key',
      ]));
    }
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Do nothing.
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
Oauth2GenerateKeyForm::$keyGen private property
Oauth2GenerateKeyForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
Oauth2GenerateKeyForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
Oauth2GenerateKeyForm::generateKeys public function Generate public and private keys.
Oauth2GenerateKeyForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Oauth2GenerateKeyForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
Oauth2GenerateKeyForm::__construct public function Oauth2GenerateKeyForm constructor.
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.