Skip to content

Instantly share code, notes, and snippets.

@philipnorton42
Last active December 13, 2020 20:51
Show Gist options
  • Save philipnorton42/99fb6c7299119405d63bad50dd9d7540 to your computer and use it in GitHub Desktop.
Save philipnorton42/99fb6c7299119405d63bad50dd9d7540 to your computer and use it in GitHub Desktop.
FloodProtectedForm example of the Drupal flood service. Take from https://www.hashbangcode.com/article/drupal-9-integrating-flood-protection-forms
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Flood\FloodInterface;
use Drupal\Component\Utility\Crypt;
class FloodProtectedForm extends FormBase
{
/**
* {@inheritdoc}
*/
public function getFormId()
{
return 'mymodule_flood_protected_form';
}
/**
* The flood service.
*
* @var \Drupal\Core\Flood\FloodInterface
*/
protected $flood;
/**
* FloodProtectedForm constructor.
*
* @param \Drupal\Core\Flood\FloodInterface $flood
* The flood service.
*/
public function __construct(FloodInterface $flood)
{
$this->flood = $flood;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container)
{
return new static(
$container->get('flood')
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
$form['text'] = [
'#type' => 'textfield',
'#title' => 'Flood protected field',
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Test',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state)
{
$text = $form_state->getValue('text');
$hashedValue = Crypt::hashBase64($text);
$floodControlUserIdentifier = $this->getRequest()->getClientIP() . $hashedValue;
if (!$this->flood->isAllowed('mymodule.flood_protected_form', 10, 3600, $floodControlUserIdentifier)) {
$form_state->setErrorByName('url', $this->t('Too many uses of this form from your IP address. This IP address is temporarily blocked. Try again later.'));
return;
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$text = $form_state->getValue('text');
$hashedValue = Crypt::hashBase64($text);
$floodControlUserIdentifier = $this->getRequest()->getClientIP() . $hashedValue;
$this->flood->register('mymodule.flood_protected_form', 3600, $floodControlUserIdentifier);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment