You are here

class UsersGenerateKeyForm in JSON Web Token Authentication (JWT) 8

Class UsersKeyForm.

Hierarchy

Expanded class hierarchy of UsersGenerateKeyForm

1 string reference to 'UsersGenerateKeyForm'
users_jwt.routing.yml in modules/users_jwt/users_jwt.routing.yml
modules/users_jwt/users_jwt.routing.yml

File

modules/users_jwt/src/Form/UsersGenerateKeyForm.php, line 18

Namespace

Drupal\users_jwt\Form
View source
class UsersGenerateKeyForm extends FormBase {

  /**
   * The user key repository service.
   *
   * @var \Drupal\users_jwt\UsersJwtKeyRepositoryInterface
   */
  protected $keyRepository;

  /**
   * Constructs a key form.
   *
   * @param \Drupal\users_jwt\UsersJwtKeyRepositoryInterface $key_repository
   *   The user key repository service.
   */
  public function __construct(UsersJwtKeyRepositoryInterface $key_repository) {
    $this->keyRepository = $key_repository;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
    if (!$user) {
      return $form;
    }
    $new_id = $user
      ->id() . '-' . $this
      ->getRequest()->server
      ->get('REQUEST_TIME');
    $key = new UsersKey($user
      ->id(), $new_id, 'RS256');
    $form['key'] = [
      '#type' => 'value',
      '#value' => $key,
    ];
    $form['user'] = [
      '#type' => 'value',
      '#value' => $user,
    ];
    $form['instructions'] = [
      '#type' => 'item',
      '#markup' => $this
        ->t('When you click the button, a new key will be generated with ID %key_id. You will save the private key, the public key will be added to your account. If you lose the private key, it cannot be recovered.', [
        '%key_id' => $key->id,
      ]),
    ];
    $form['alg'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Key Type'),
      '#description' => $this
        ->t('The type of key to generate.'),
      '#options' => $this->keyRepository
        ->algorithmOptions(),
      '#size' => 1,
      '#default_value' => $key->alg,
      '#weight' => 10,
      '#required' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
      '#weight' => 30,
    ];
    $form['actions']['download'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Generate'),
    ];
    $cancel_url = Url::fromRoute('users_jwt.key_list', [
      'user' => $user
        ->id(),
    ]);
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
      '#url' => $cancel_url,
    ];
    $form['#attached']['library'][] = 'users_jwt/download_redirect';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $key = $form_state
      ->getValue('key');
    $alg = $form_state
      ->getValue('alg');
    if ($alg === 'RS256') {
      $config = [
        'private_key_bits' => 4096,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
      ];
      $private_key = openssl_pkey_new($config);
      $pub = openssl_pkey_get_details($private_key);
      $pubkey = $pub['key'];
      openssl_pkey_export($private_key, $out);
    }
    else {
      throw new \InvalidArgumentException(sprintf('Unknown alg %s', $alg));
    }
    $this->keyRepository
      ->saveKey($key->uid, $key->id, $alg, $pubkey);

    /** @var \Drupal\user\UserInterface $user */
    $user = $form_state
      ->getValue('user');
    $filename = $user
      ->getAccountName() . '__private-key__' . $key->id . '.key';
    $response = Response::create($out);
    $response
      ->setPrivate();

    // Clear the cookie from the browser that is set in JavaScript.
    $response->headers
      ->clearCookie('users_jwt_download', '/', NULL, FALSE, FALSE);
    $disposition = $response->headers
      ->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
    $response->headers
      ->set('Content-Disposition', $disposition);
    $form_state
      ->setResponse($response);
  }

}

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.
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.
UsersGenerateKeyForm::$keyRepository protected property The user key repository service.
UsersGenerateKeyForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UsersGenerateKeyForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UsersGenerateKeyForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UsersGenerateKeyForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UsersGenerateKeyForm::__construct public function Constructs a key form.