You are here

class ShieldSettingsForm in Shield 8

Configure site information settings for this site.

Hierarchy

Expanded class hierarchy of ShieldSettingsForm

1 string reference to 'ShieldSettingsForm'
shield.routing.yml in ./shield.routing.yml
shield.routing.yml

File

src/Form/ShieldSettingsForm.php, line 16

Namespace

Drupal\shield\Form
View source
class ShieldSettingsForm extends ConfigFormBase {

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The key type manager, if exists.
   *
   * @var \Drupal\key\Plugin\KeyPluginManager|null
   */
  protected $keyTypeManager;

  /**
   * ShieldSettingsForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   * @param \Drupal\key\Plugin\KeyPluginManager|null $keyTypeManager
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $moduleHandler, KeyPluginManager $keyTypeManager = NULL) {
    parent::__construct($config_factory);
    $this->moduleHandler = $moduleHandler;
    $this->keyTypeManager = $keyTypeManager;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *
   * @return \Drupal\Core\Form\ConfigFormBase|\Drupal\shield\Form\ShieldSettingsForm|static
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('module_handler'), $container
      ->get('plugin.manager.key.key_type', ContainerInterface::NULL_ON_INVALID_REFERENCE));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'shield.settings',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $shield_config = $this
      ->config('shield.settings');

    // Submitted form values should be nested.
    $form['#tree'] = TRUE;
    $form['description'] = [
      '#type' => 'item',
      '#title' => $this
        ->t('Shield settings'),
      '#description' => $this
        ->t('Set up credentials for an authenticated user. You can also decide whether you want to print out the credentials or not.'),
    ];
    $form['general'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('General settings'),
    ];
    $form['general']['shield_enable'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable Shield'),
      '#description' => $this
        ->t('Enable/Disable shield functionality. All other settings are ignored if this is not checked.'),
      '#default_value' => $shield_config
        ->get('shield_enable'),
    ];
    $form['general']['shield_allow_cli'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Allow command line access'),
      '#description' => $this
        ->t('When the site is accessed from command line (e.g. from Drush, cron), the shield should not work.'),
      '#default_value' => $shield_config
        ->get('allow_cli'),
    ];
    $form['general']['whitelist'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('IP Whitelist'),
      '#description' => $this
        ->t("Enter list of IP's for which shield should not be shown, one per line. You can use Network ranges in the format 'IP/Range'.<br><em>Warning: Whitelist interferes with reverse proxy caching! @strong_style_tag Do not use whitelist if reverse proxy caching is in use!</strong></em>", [
        '@strong_style_tag' => Markup::create("<strong style='color:red'>"),
      ]),
      '#default_value' => $shield_config
        ->get('whitelist'),
      '#placeholder' => $this
        ->t("Example:\n192.168.0.1/24\n127.0.0.1"),
    ];
    $form['general']['shield_domains'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Whitelist Domains'),
      '#description' => $this
        ->t('Enter list of domain host names for which shield should not be shown, one per line.'),
      '#default_value' => $shield_config
        ->get('domains'),
      '#placeholder' => $this
        ->t("Example:\nexample.com\ndomain.in"),
    ];
    $form['credentials'] = [
      '#id' => 'credentials',
      '#type' => 'details',
      '#title' => $this
        ->t('Credentials'),
      '#open' => TRUE,
    ];
    $credential_provider = $shield_config
      ->get('credential_provider');
    $credential_provider = $form_state
      ->hasValue([
      'credentials',
      'credential_provider',
    ]) ? $form_state
      ->getValue([
      'credentials',
      'credential_provider',
    ]) : $credential_provider;
    $form['credentials']['credential_provider'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Credential provider'),
      '#options' => [
        'shield' => 'Shield',
      ],
      '#default_value' => $credential_provider,
      '#ajax' => [
        'callback' => [
          $this,
          'ajaxCallback',
        ],
        'wrapper' => 'credentials_configuration',
        'method' => 'replace',
        'effect' => 'fade',
      ],
    ];
    $form['credentials']['providers'] = [
      '#type' => 'item',
      '#id' => 'credentials_configuration',
    ];
    if ($this->keyTypeManager) {
      $form['credentials']['credential_provider']['#options']['key'] = $this
        ->t('Key Module');
      if ($this->keyTypeManager
        ->hasDefinition('user_password')) {
        $form['credentials']['credential_provider']['#options']['multikey'] = $this
          ->t('Key Module (user/password)');
      }
    }
    if ($credential_provider == 'shield') {
      $form['credentials']['providers']['shield']['user'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('User'),
        '#default_value' => $shield_config
          ->get('credentials.shield.user'),
        '#description' => $this
          ->t('Leave blank to disable authentication.'),
      ];
      $form['credentials']['providers']['shield']['pass'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Password'),
        '#default_value' => $shield_config
          ->get('credentials.shield.pass'),
      ];
    }
    elseif ($credential_provider == 'key') {
      $form['credentials']['providers']['key']['user'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('User'),
        '#default_value' => $shield_config
          ->get('credentials.key.user'),
        '#required' => TRUE,
      ];
      $form['credentials']['providers']['key']['pass_key'] = [
        '#type' => 'key_select',
        '#title' => $this
          ->t('Password'),
        '#default_value' => $shield_config
          ->get('credentials.key.pass_key'),
        '#empty_option' => $this
          ->t('- Please select -'),
        '#key_filters' => [
          'type' => 'authentication',
        ],
        '#required' => TRUE,
      ];
    }
    elseif ($credential_provider == 'multikey') {
      $form['credentials']['providers']['multikey']['user_pass_key'] = [
        '#type' => 'key_select',
        '#title' => $this
          ->t('User/password'),
        '#default_value' => $shield_config
          ->get('credentials.multikey.user_pass_key'),
        '#empty_option' => $this
          ->t('- Please select -'),
        '#key_filters' => [
          'type' => 'user_password',
        ],
        '#required' => TRUE,
      ];
    }
    $form['shield_print'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Authentication message'),
      '#description' => $this
        ->t("The message to print in the authentication request popup. You can use [user] and [pass] to print the user and the password respectively. You can leave it empty, if you don't want to print out any special message to the users."),
      '#default_value' => $shield_config
        ->get('print'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $shield_config = $this
      ->config('shield.settings');
    $credential_provider = $form_state
      ->getValue([
      'credentials',
      'credential_provider',
    ]);
    $shield_config
      ->set('allow_cli', $form_state
      ->getValue([
      'general',
      'shield_allow_cli',
    ]))
      ->set('shield_enable', $form_state
      ->getValue([
      'general',
      'shield_enable',
    ]))
      ->set('whitelist', $form_state
      ->getValue([
      'general',
      'whitelist',
    ]))
      ->set('domains', $form_state
      ->getValue([
      'general',
      'shield_domains',
    ]))
      ->set('print', $form_state
      ->getValue('shield_print'))
      ->set('credential_provider', $credential_provider);
    $credentials = $form_state
      ->getValue([
      'credentials',
      'providers',
      $credential_provider,
    ]);
    $shield_config
      ->set('credentials', [
      $credential_provider => $credentials,
    ]);
    $shield_config
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Ajax callback for the credential dependent configuration options.
   *
   * @return array
   *   The form element containing the configuration options.
   */
  public static function ajaxCallback($form, FormStateInterface $form_state) {
    return $form['credentials']['providers'];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
ShieldSettingsForm::$keyTypeManager protected property The key type manager, if exists.
ShieldSettingsForm::$moduleHandler protected property The module handler.
ShieldSettingsForm::ajaxCallback public static function Ajax callback for the credential dependent configuration options.
ShieldSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ShieldSettingsForm::create public static function Overrides ConfigFormBase::create
ShieldSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ShieldSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ShieldSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
ShieldSettingsForm::__construct public function ShieldSettingsForm constructor. Overrides ConfigFormBase::__construct
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.