You are here

public function UsersKeyForm::buildForm in JSON Web Token Authentication (JWT) 8

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

modules/users_jwt/src/Form/UsersKeyForm.php, line 53

Class

UsersKeyForm
Class UsersKeyForm.

Namespace

Drupal\users_jwt\Form

Code

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;
}