You are here

class ReCaptchaV3SettingsForm in reCAPTCHA v3 8

Configure the google reCAPTCHA v3 api and fallback challenge.

Hierarchy

Expanded class hierarchy of ReCaptchaV3SettingsForm

1 string reference to 'ReCaptchaV3SettingsForm'
recaptcha_v3.routing.yml in ./recaptcha_v3.routing.yml
recaptcha_v3.routing.yml

File

src/Form/ReCaptchaV3SettingsForm.php, line 16

Namespace

Drupal\recaptcha_v3\Form
View source
class ReCaptchaV3SettingsForm extends ConfigFormBase {

  /**
   * The library discovery service.
   *
   * @var \Drupal\Core\Asset\LibraryDiscoveryInterface
   */
  protected $libraryDiscovery;

  /**
   * The element info manager.
   *
   * @var \Drupal\Core\Render\ElementInfoManager
   */
  protected $elementInfoManager;

  /**
   * The CAPTCHA helper service.
   *
   * @var \Drupal\captcha\Service\CaptchaService
   */
  protected $captchaService;

  /**
   * ReCaptchaV3SettingsForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory service.
   * @param \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery
   *   Library discovery service.
   * @param \Drupal\Core\Render\ElementInfoManager $element_info_manager
   *   Element info manager service.
   * @param \Drupal\captcha\Service\CaptchaService $captcha_service
   *   Captcha service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LibraryDiscoveryInterface $library_discovery, ElementInfoManager $element_info_manager, CaptchaService $captcha_service) {
    parent::__construct($config_factory);
    $this->libraryDiscovery = $library_discovery;
    $this->elementInfoManager = $element_info_manager;
    $this->captchaService = $captcha_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('library.discovery'), $container
      ->get('plugin.manager.element_info'), $container
      ->get('captcha.helper'));
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('recaptcha_v3.settings');
    $form['site_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Site key'),
      '#default_value' => $config
        ->get('site_key'),
      '#maxlength' => 40,
      '#description' => $this
        ->t('The site key given to you when you <a href="@url">register for reCAPTCHA</a>.', [
        '@url' => 'https://www.google.com/recaptcha/admin',
      ]),
      '#required' => TRUE,
    ];
    $form['secret_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Secret key'),
      '#default_value' => $config
        ->get('secret_key'),
      '#maxlength' => 40,
      '#description' => $this
        ->t('The secret key given to you when you <a href="@url">register for reCAPTCHA</a>.', [
        '@url' => 'https://www.google.com/recaptcha/admin',
      ]),
      '#required' => TRUE,
    ];
    $form['verify_hostname'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Local domain name validation'),
      '#default_value' => $config
        ->get('verify_hostname'),
      '#description' => $this
        ->t('Checks the hostname on your server when verifying a solution. Enable this validation only, if <em>Verify the origin of reCAPTCHA solutions</em> is unchecked for your key pair. Provides crucial security by verifying requests come from one of your listed domains.'),
    ];
    $challenges = $this->captchaService
      ->getAvailableChallengeTypes(FALSE);

    // Remove recaptcha v3 challenges from the list of available
    // fallback challenges.
    $challenges = array_filter($challenges, static function ($captcha_type) {
      return !(strpos($captcha_type, 'recaptcha_v3') === 0);
    }, ARRAY_FILTER_USE_KEY);
    $form['default_challenge'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default fallback challenge type'),
      '#description' => $this
        ->t('Select the default fallback challenge type on verification fail.'),
      '#options' => $challenges,
      '#default_value' => $config
        ->get('default_challenge'),
      '#empty_option' => $this
        ->t('- None -'),
      '#empty_value' => '',
    ];
    $form['error_message'] = [
      '#type' => 'textfield',
      '#size' => 128,
      '#title' => $this
        ->t('Error message'),
      '#description' => $this
        ->t('This message will be displayed to user in case of failed recaptcha v3 verification.'),
      '#default_value' => $config
        ->get('error_message'),
    ];
    $form['cacheable'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Cacheable'),
      '#description' => $this
        ->t('Make captcha cacheble: can lead to some validation errors like "unknown CAPTCHA session ID".'),
      '#default_value' => $config
        ->get('cacheable'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $config = $this
      ->config('recaptcha_v3.settings');

    // If site key have been changed,
    // then need to rebuild site libraries and elements.
    if ($config
      ->get('site_key') !== $values['site_key']) {
      $this->libraryDiscovery
        ->clearCachedDefinitions();
      $this->elementInfoManager
        ->clearCachedDefinitions();
    }
    $this
      ->config('recaptcha_v3.settings')
      ->set('site_key', $values['site_key'])
      ->set('secret_key', $values['secret_key'])
      ->set('verify_hostname', $values['verify_hostname'])
      ->set('default_challenge', $values['default_challenge'])
      ->set('error_message', $values['error_message'])
      ->set('cacheable', $values['cacheable'])
      ->save();
    parent::submitForm($form, $form_state);
  }

}

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.
ReCaptchaV3SettingsForm::$captchaService protected property The CAPTCHA helper service.
ReCaptchaV3SettingsForm::$elementInfoManager protected property The element info manager.
ReCaptchaV3SettingsForm::$libraryDiscovery protected property The library discovery service.
ReCaptchaV3SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ReCaptchaV3SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
ReCaptchaV3SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ReCaptchaV3SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ReCaptchaV3SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
ReCaptchaV3SettingsForm::__construct public function ReCaptchaV3SettingsForm constructor. Overrides ConfigFormBase::__construct
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.