class UserKeyAuthForm in Key auth 8
Class UserKeyAuthForm.
Provides a form to manage the user's key for authentication.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait- class \Drupal\key_auth\Form\UserKeyAuthForm
 
Expanded class hierarchy of UserKeyAuthForm
1 string reference to 'UserKeyAuthForm'
File
- src/Form/ UserKeyAuthForm.php, line 20 
Namespace
Drupal\key_auth\FormView source
class UserKeyAuthForm extends FormBase {
  /**
   * The key authentication service.
   *
   * @var \Drupal\key_auth\KeyAuthInterface
   */
  protected $keyAuth;
  /**
   * The module configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;
  /**
   * Constructs a new UserKeyAuthForm.
   *
   * @param \Drupal\key_auth\KeyAuthInterface $key_auth
   *   The key authentication service.
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory service.
   */
  public function __construct(KeyAuthInterface $key_auth, ConfigFactory $config_factory) {
    $this->keyAuth = $key_auth;
    $this->config = $config_factory
      ->get('key_auth.settings');
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('key_auth'), $container
      ->get('config.factory'));
  }
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_key_auth_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
    // Extract the user's key.
    $key = $user->api_key->value;
    // Store the user ID.
    $form['#uid'] = $user
      ->id();
    $form['key'] = [
      'label' => [
        '#type' => 'html_tag',
        '#tag' => 'h3',
        '#value' => $this
          ->t('Key'),
      ],
      'key' => [
        '#type' => 'item',
        '#markup' => $key ? $key : $this
          ->t('You currently do not have a key'),
      ],
    ];
    $form['auth'] = [
      'label' => [
        '#type' => 'html_tag',
        '#tag' => 'h3',
        '#value' => $this
          ->t('Authentication options'),
      ],
      '#access' => (bool) $key,
    ];
    // Check if header detection is enabled.
    if (in_array(KeyAuth::DETECTION_METHOD_HEADER, $this->config
      ->get('detection_methods'))) {
      $form['auth']['header'] = [
        'label' => [
          '#type' => 'html_tag',
          '#tag' => 'h5',
          '#value' => $this
            ->t('Header'),
        ],
        'instructions' => [
          '#type' => 'item',
          '#markup' => $this
            ->t('Include the following header in your API requests.'),
        ],
        'example' => [
          '#type' => 'html_tag',
          '#tag' => 'pre',
          '#value' => $this->config
            ->get('param_name') . ': ' . $key,
        ],
      ];
    }
    // Check if query detection is enabled.
    if (in_array(KeyAuth::DETECTION_METHOD_QUERY, $this->config
      ->get('detection_methods'))) {
      $form['auth']['query'] = [
        'label' => [
          '#type' => 'html_tag',
          '#tag' => 'h5',
          '#value' => $this
            ->t('Query'),
        ],
        'instructions' => [
          '#type' => 'item',
          '#markup' => $this
            ->t('Include the following query in the URL of your API requests.'),
        ],
        'example' => [
          '#type' => 'html_tag',
          '#tag' => 'pre',
          '#value' => '?' . $this->config
            ->get('param_name') . '=' . $key,
        ],
      ];
    }
    $form['actions'] = [
      'new' => [
        '#type' => 'submit',
        '#value' => $this
          ->t('Generate new key'),
      ],
      'delete' => [
        '#type' => 'submit',
        '#value' => $this
          ->t('Delete current key'),
        '#access' => (bool) $key,
        '#submit' => [
          '::deleteKey',
        ],
      ],
    ];
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Generate a new key.
    User::load($form['#uid'])
      ->set('api_key', $this->keyAuth
      ->generateKey())
      ->save();
    // Alert the user.
    $this
      ->messenger()
      ->addMessage($this
      ->t('A new key has been generated.'));
  }
  /**
   * Submit handler to delete the key.
   */
  public function deleteKey(array &$form, FormStateInterface $form_state) {
    // Delete the key.
    User::load($form['#uid'])
      ->set('api_key', NULL)
      ->save();
    // Alert the user.
    $this
      ->messenger()
      ->addMessage($this
      ->t('Your key has been deleted.'));
  }
  /**
   * Access handler for the form.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user entity being edited.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function checkAccess(UserInterface $user) {
    // Load the current user.
    $current_user = User::load($this
      ->currentUser()
      ->id());
    // Check if the user being edited is not the current user.
    if ($user
      ->id() != $current_user
      ->id()) {
      // Check admin-access.
      $access = AccessResult::allowedIfHasPermission($current_user, 'administer users');
    }
    else {
      $access = AccessResult::allowedIf($this->keyAuth
        ->access($current_user));
    }
    // Add caching.
    $access
      ->addCacheContexts([
      'user.permissions',
    ]);
    $access
      ->addCacheableDependency($user);
    return $access;
  }
}Members
| Name   | Modifiers | Type | Description | Overrides | 
|---|---|---|---|---|
| DependencySerializationTrait:: | protected | property | An array of entity type IDs keyed by the property name of their storages. | |
| DependencySerializationTrait:: | protected | property | An array of service IDs keyed by property name used for serialization. | |
| DependencySerializationTrait:: | public | function | 1 | |
| DependencySerializationTrait:: | public | function | 2 | |
| FormBase:: | protected | property | The config factory. | 1 | 
| FormBase:: | protected | property | The request stack. | 1 | 
| FormBase:: | protected | property | The route match. | |
| FormBase:: | protected | function | Retrieves a configuration object. | |
| FormBase:: | protected | function | Gets the config factory for this form. | 1 | 
| FormBase:: | private | function | Returns the service container. | |
| FormBase:: | protected | function | Gets the current user. | |
| FormBase:: | protected | function | Gets the request object. | |
| FormBase:: | protected | function | Gets the route match. | |
| FormBase:: | protected | function | Gets the logger for a specific channel. | |
| FormBase:: | protected | function | Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: | |
| FormBase:: | public | function | Resets the configuration factory. | |
| FormBase:: | public | function | Sets the config factory for this form. | |
| FormBase:: | public | function | Sets the request stack object to use. | |
| FormBase:: | public | function | Form validation handler. Overrides FormInterface:: | 62 | 
| LinkGeneratorTrait:: | protected | property | The link generator. | 1 | 
| LinkGeneratorTrait:: | protected | function | Returns the link generator. | |
| LinkGeneratorTrait:: | protected | function | Renders a link to a route given a route name and its parameters. | |
| LinkGeneratorTrait:: | public | function | Sets the link generator service. | |
| LoggerChannelTrait:: | protected | property | The logger channel factory service. | |
| LoggerChannelTrait:: | protected | function | Gets the logger for a specific channel. | |
| LoggerChannelTrait:: | public | function | Injects the logger channel factory. | |
| MessengerTrait:: | protected | property | The messenger. | 29 | 
| MessengerTrait:: | public | function | Gets the messenger. | 29 | 
| MessengerTrait:: | public | function | Sets the messenger. | |
| RedirectDestinationTrait:: | protected | property | The redirect destination service. | 1 | 
| RedirectDestinationTrait:: | protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
| RedirectDestinationTrait:: | protected | function | Returns the redirect destination service. | |
| RedirectDestinationTrait:: | public | function | Sets the redirect destination service. | |
| StringTranslationTrait:: | protected | property | The string translation service. | 1 | 
| StringTranslationTrait:: | protected | function | Formats a string containing a count of items. | |
| StringTranslationTrait:: | protected | function | Returns the number of plurals supported by a given language. | |
| StringTranslationTrait:: | protected | function | Gets the string translation service. | |
| StringTranslationTrait:: | public | function | Sets the string translation service to use. | 2 | 
| StringTranslationTrait:: | protected | function | Translates a string to the current language or to a given language. | |
| UrlGeneratorTrait:: | protected | property | The url generator. | |
| UrlGeneratorTrait:: | protected | function | Returns the URL generator service. | |
| UrlGeneratorTrait:: | public | function | Sets the URL generator service. | |
| UrlGeneratorTrait:: | protected | function | Generates a URL or path for a specific route based on the given parameters. | |
| UserKeyAuthForm:: | protected | property | The module configuration. | |
| UserKeyAuthForm:: | protected | property | The key authentication service. | |
| UserKeyAuthForm:: | public | function | Form constructor. Overrides FormInterface:: | |
| UserKeyAuthForm:: | public | function | Access handler for the form. | |
| UserKeyAuthForm:: | public static | function | Instantiates a new instance of this class. Overrides FormBase:: | |
| UserKeyAuthForm:: | public | function | Submit handler to delete the key. | |
| UserKeyAuthForm:: | public | function | Returns a unique string identifying the form. Overrides FormInterface:: | |
| UserKeyAuthForm:: | public | function | Form submission handler. Overrides FormInterface:: | |
| UserKeyAuthForm:: | public | function | Constructs a new UserKeyAuthForm. | 
