You are here

class UsersKeyForm in JSON Web Token Authentication (JWT) 8

Class UsersKeyForm.

Hierarchy

Expanded class hierarchy of UsersKeyForm

1 string reference to 'UsersKeyForm'
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/UsersKeyForm.php, line 17

Namespace

Drupal\users_jwt\Form
View source
class UsersKeyForm 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, $key_id = NULL, UserInterface $user = NULL) {
    if (!$user) {
      return $form;
    }
    if ($key_id) {
      $key = $this->keyRepository
        ->getKey($key_id);
      if (!$key || $key->uid != $user
        ->id()) {
        throw new NotFoundHttpException();
      }
    }
    else {
      $new_id = $user
        ->id() . '-' . $this
        ->getRequest()->server
        ->get('REQUEST_TIME');
      $key = new UsersKey($user
        ->id(), $new_id, 'RS256');
    }
    $form['is_new'] = [
      '#type' => 'value',
      '#value' => !$key_id,
    ];
    $form['key'] = [
      '#type' => 'value',
      '#value' => $key,
    ];
    $form['id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Key ID'),
      '#description' => $this
        ->t('The unique key ID'),
      '#maxlength' => 64,
      '#size' => 30,
      '#default_value' => $key->id,
      '#weight' => 0,
      '#required' => TRUE,
      // An administrator is allowed to set the ID for a new key.
      '#disabled' => !$this
        ->currentUser()
        ->hasPermission('administer users') || $key_id,
    ];
    $form['alg'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Key Type'),
      '#description' => $this
        ->t('The type of public key being added.'),
      '#options' => $this->keyRepository
        ->algorithmOptions(),
      '#size' => 1,
      '#default_value' => $key->alg,
      '#weight' => 10,
      '#required' => TRUE,
    ];
    $form['pubkey'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Public Key'),
      '#description' => $this
        ->t('The public key value.'),
      '#default_value' => $key->pubkey,
      '#weight' => 20,
      '#required' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
      '#weight' => 30,
    ];
    $form['actions']['save'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    $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,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $is_new = $form_state
      ->getValue('is_new');
    if ($is_new) {
      $id = trim($form_state
        ->getValue('id'));
      if ($this->keyRepository
        ->getKey($id)) {
        $form_state
          ->setErrorByName('id', $this
          ->t('%id is already in use as an ID', [
          '%id' => $id,
        ]));
      }
    }
    $alg = $form_state
      ->getValue('alg');
    $pubkey = trim($form_state
      ->getValue('pubkey'));
    if ($alg === 'RS256') {
      $key_resource = openssl_pkey_get_public($pubkey);
      $details = $key_resource ? openssl_pkey_get_details($key_resource) : FALSE;
      if ($details === FALSE || $details['type'] !== OPENSSL_KEYTYPE_RSA) {
        $form_state
          ->setErrorByName('pubkey', $this
          ->t('This does not look like a PEM formatted RSA public key'));
      }
      else {
        if ($details['bits'] < 2048) {
          $form_state
            ->setErrorByName('pubkey', $this
            ->t('You need to submit at least a 2048 bit key'));
        }
      }
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $key = $form_state
      ->getValue('key');
    $is_new = $form_state
      ->getValue('is_new');
    if ($is_new) {
      $key->id = trim($form_state
        ->getValue('id'));
    }
    $this->keyRepository
      ->saveKey($key->uid, $key->id, $form_state
      ->getValue('alg'), $form_state
      ->getValue('pubkey'));
    $this
      ->messenger()
      ->addStatus('Saved key %key_id', [
      '%key_id' => $key->id,
    ]);
    $form_state
      ->setRedirect('users_jwt.key_list', [
      'user' => $key->uid,
    ]);
  }

}

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