You are here

class UserKeyAuthForm in Key auth 8

Class UserKeyAuthForm.

Provides a form to manage the user's key for authentication.

Hierarchy

Expanded class hierarchy of UserKeyAuthForm

1 string reference to 'UserKeyAuthForm'
key_auth.routing.yml in ./key_auth.routing.yml
key_auth.routing.yml

File

src/Form/UserKeyAuthForm.php, line 20

Namespace

Drupal\key_auth\Form
View 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

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.
UserKeyAuthForm::$config protected property The module configuration.
UserKeyAuthForm::$keyAuth protected property The key authentication service.
UserKeyAuthForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UserKeyAuthForm::checkAccess public function Access handler for the form.
UserKeyAuthForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserKeyAuthForm::deleteKey public function Submit handler to delete the key.
UserKeyAuthForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserKeyAuthForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UserKeyAuthForm::__construct public function Constructs a new UserKeyAuthForm.