better registration form and accompt creation

This commit is contained in:
2018-04-25 15:38:49 +02:00
parent 956d8fb1ec
commit 50f0d72e62
40 changed files with 2853 additions and 5 deletions
@@ -0,0 +1,329 @@
<?php
namespace Drupal\honeypot\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Drupal\comment\Entity\CommentType;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for Honeypot module routes.
*/
class HoneypotSettingsController extends ConfigFormBase {
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* A cache backend interface.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cache;
/**
* Constructs a settings controller.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info service.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend interface.
*/
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, CacheBackendInterface $cache_backend) {
parent::__construct($config_factory);
$this->moduleHandler = $module_handler;
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->cache = $cache_backend;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('module_handler'),
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('cache.default')
);
}
/**
* Get a value from the retrieved form settings array.
*/
public function getFormSettingsValue($form_settings, $form_id) {
// If there are settings in the array and the form ID already has a setting,
// return the saved setting for the form ID.
if (!empty($form_settings) && isset($form_settings[$form_id])) {
return $form_settings[$form_id];
}
// Default to false.
else {
return 0;
}
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['honeypot.settings'];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'honeypot_settings_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Honeypot Configuration.
$form['configuration'] = [
'#type' => 'fieldset',
'#title' => $this->t('Honeypot Configuration'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
];
$form['configuration']['protect_all_forms'] = [
'#type' => 'checkbox',
'#title' => $this->t('Protect all forms with Honeypot'),
'#description' => $this->t('Enable Honeypot protection for ALL forms on this site (it is best to only enable Honeypot for the forms you need below).'),
'#default_value' => $this->config('honeypot.settings')->get('protect_all_forms'),
];
$form['configuration']['protect_all_forms']['#description'] .= '<br />' . $this->t('<strong>Page caching will be disabled on any page where a form is present if the Honeypot time limit is not set to 0.</strong>');
$form['configuration']['log'] = [
'#type' => 'checkbox',
'#title' => $this->t('Log blocked form submissions'),
'#description' => $this->t('Log submissions that are blocked due to Honeypot protection.'),
'#default_value' => $this->config('honeypot.settings')->get('log'),
];
$form['configuration']['element_name'] = [
'#type' => 'textfield',
'#title' => $this->t('Honeypot element name'),
'#description' => $this->t("The name of the Honeypot form field. It's usually most effective to use a generic name like email, homepage, or link, but this should be changed if it interferes with fields that are already in your forms. Must not contain spaces or special characters."),
'#default_value' => $this->config('honeypot.settings')->get('element_name'),
'#required' => TRUE,
'#size' => 30,
];
$form['configuration']['time_limit'] = [
'#type' => 'textfield',
'#title' => $this->t('Honeypot time limit'),
'#description' => $this->t('Minimum time required before form should be considered entered by a human instead of a bot. Set to 0 to disable.'),
'#default_value' => $this->config('honeypot.settings')->get('time_limit'),
'#required' => TRUE,
'#size' => 5,
'#field_suffix' => $this->t('seconds'),
];
$form['configuration']['time_limit']['#description'] .= '<br />' . $this->t('<strong>Page caching will be disabled if there is a form protected by time limit on the page.</strong>');
// Honeypot Enabled forms.
$form_settings = $this->config('honeypot.settings')->get('form_settings');
$form['form_settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Honeypot Enabled Forms'),
'#description' => $this->t("Check the boxes next to individual forms on which you'd like Honeypot protection enabled."),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#tree' => TRUE,
'#states' => [
// Hide this fieldset when all forms are protected.
'invisible' => [
'input[name="protect_all_forms"]' => ['checked' => TRUE],
],
],
];
// Generic forms.
$form['form_settings']['general_forms'] = ['#markup' => '<h5>' . $this->t('General Forms') . '</h5>'];
// User register form.
$form['form_settings']['user_register_form'] = [
'#type' => 'checkbox',
'#title' => $this->t('User Registration form'),
'#default_value' => $this->getFormSettingsValue($form_settings, 'user_register_form'),
];
// User password form.
$form['form_settings']['user_pass'] = [
'#type' => 'checkbox',
'#title' => $this->t('User Password Reset form'),
'#default_value' => $this->getFormSettingsValue($form_settings, 'user_pass'),
];
// If contact.module enabled, add contact forms.
if ($this->moduleHandler->moduleExists('contact')) {
$form['form_settings']['contact_forms'] = ['#markup' => '<h5>' . $this->t('Contact Forms') . '</h5>'];
$bundles = $this->entityTypeBundleInfo->getBundleInfo('contact_message');
$formController = $this->entityTypeManager->getFormObject('contact_message', 'default');
foreach ($bundles as $bundle_key => $bundle) {
$stub = $this->entityTypeManager->getStorage('contact_message')->create([
'contact_form' => $bundle_key,
]);
$formController->setEntity($stub);
$form_id = $formController->getFormId();
$form['form_settings'][$form_id] = [
'#type' => 'checkbox',
'#title' => Html::escape($bundle['label']),
'#default_value' => $this->getFormSettingsValue($form_settings, $form_id),
];
}
}
// Node types for node forms.
if ($this->moduleHandler->moduleExists('node')) {
$types = NodeType::loadMultiple();
if (!empty($types)) {
// Node forms.
$form['form_settings']['node_forms'] = ['#markup' => '<h5>' . $this->t('Node Forms') . '</h5>'];
foreach ($types as $type) {
$id = 'node_' . $type->get('type') . '_form';
$form['form_settings'][$id] = [
'#type' => 'checkbox',
'#title' => $this->t('@name node form', ['@name' => $type->label()]),
'#default_value' => $this->getFormSettingsValue($form_settings, $id),
];
}
}
}
// Comment types for comment forms.
if ($this->moduleHandler->moduleExists('comment')) {
$types = CommentType::loadMultiple();
if (!empty($types)) {
$form['form_settings']['comment_forms'] = ['#markup' => '<h5>' . $this->t('Comment Forms') . '</h5>'];
foreach ($types as $type) {
$id = 'comment_' . $type->id() . '_form';
$form['form_settings'][$id] = [
'#type' => 'checkbox',
'#title' => $this->t('@name comment form', ['@name' => $type->label()]),
'#default_value' => $this->getFormSettingsValue($form_settings, $id),
];
}
}
}
// Store the keys we want to save in configuration when form is submitted.
$keys_to_save = array_keys($form['configuration']);
foreach ($keys_to_save as $key => $key_to_save) {
if (strpos($key_to_save, '#') !== FALSE) {
unset($keys_to_save[$key]);
}
}
$form_state->setStorage(['keys' => $keys_to_save]);
// For now, manually add submit button. Hopefully, by the time D8 is
// released, there will be something like system_settings_form() in D7.
$form['actions']['#type'] = 'container';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save configuration'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Make sure the time limit is a positive integer or 0.
$time_limit = $form_state->getValue('time_limit');
if ((is_numeric($time_limit) && $time_limit > 0) || $time_limit === '0') {
if (ctype_digit($time_limit)) {
// Good to go.
}
else {
$form_state->setErrorByName('time_limit', $this->t("The time limit must be a positive integer or 0."));
}
}
else {
$form_state->setErrorByName('time_limit', $this->t("The time limit must be a positive integer or 0."));
}
// Make sure Honeypot element name only contains A-Z, 0-9.
if (!preg_match("/^[-_a-zA-Z0-9]+$/", $form_state->getValue('element_name'))) {
$form_state->setErrorByName('element_name', $this->t("The element name cannot contain spaces or other special characters."));
}
// Make sure Honeypot element name starts with a letter.
if (!preg_match("/^[a-zA-Z].+$/", $form_state->getValue('element_name'))) {
$form_state->setErrorByName('element_name', $this->t("The element name must start with a letter."));
}
// Make sure Honeypot element name isn't one of the reserved names.
$reserved_element_names = [
'name',
'pass',
'website',
];
if (in_array($form_state->getValue('element_name'), $reserved_element_names)) {
$form_state->setErrorByName('element_name', $this->t("The element name cannot match one of the common Drupal form field names (e.g. @names).", ['@names' => implode(', ', $reserved_element_names)]));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('honeypot.settings');
$storage = $form_state->getStorage();
// Save all the Honeypot configuration items from $form_state.
foreach ($form_state->getValues() as $key => $value) {
if (in_array($key, $storage['keys'])) {
$config->set($key, $value);
}
}
// Save the honeypot forms from $form_state into a 'form_settings' array.
$config->set('form_settings', $form_state->getValue('form_settings'));
$config->save();
// Clear the honeypot protected forms cache.
$this->cache->delete('honeypot_protected_forms');
// Tell the user the settings have been saved.
drupal_set_message($this->t('The configuration options have been saved.'));
}
}
@@ -0,0 +1,96 @@
<?php
namespace Drupal\honeypot\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Test Honeypot spam protection admin form functionality.
*
* @group honeypot
*/
class HoneypotAdminFormTest extends WebTestBase {
protected $adminUser;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['honeypot'];
/**
* Setup before test.
*/
public function setUp() {
// Enable modules required for this test.
parent::setUp();
// Set up admin user.
$this->adminUser = $this->drupalCreateUser([
'administer honeypot',
'bypass honeypot protection',
]);
}
/**
* Test a valid element name.
*/
public function testElementNameUpdateSuccess() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Set up form and submit it.
$edit['element_name'] = "test";
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
// Form should have been submitted successfully.
$this->assertText(t('The configuration options have been saved.'), 'Honeypot element name assertion works for valid names.');
// Set up form and submit it.
$edit['element_name'] = "test-1";
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
// Form should have been submitted successfully.
$this->assertText(t('The configuration options have been saved.'), 'Honeypot element name assertion works for valid names with dashes and numbers.');
}
/**
* Test an invalid element name (invalid first character).
*/
public function testElementNameUpdateFirstCharacterFail() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Set up form and submit it.
$edit['element_name'] = "1test";
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
// Form submission should fail.
$this->assertText(t('The element name must start with a letter.'), 'Honeypot element name assertion works for invalid names.');
}
/**
* Test an invalid element name (invalid character in name).
*/
public function testElementNameUpdateInvalidCharacterFail() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Set up form and submit it.
$edit['element_name'] = "special-character-&";
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
// Form submission should fail.
$this->assertText(t('The element name cannot contain spaces or other special characters.'), 'Honeypot element name assertion works for invalid names with special characters.');
// Set up form and submit it.
$edit['element_name'] = "space in name";
$this->drupalPostForm('admin/config/content/honeypot', $edit, t('Save configuration'));
// Form submission should fail.
$this->assertText(t('The element name cannot contain spaces or other special characters.'), 'Honeypot element name assertion works for invalid names with spaces.');
}
}
@@ -0,0 +1,137 @@
<?php
namespace Drupal\honeypot\Tests;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\contact\Entity\ContactForm;
use Drupal\simpletest\WebTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Tests page caching on Honeypot protected forms.
*
* @group honeypot
*/
class HoneypotFormCacheTest extends WebTestBase {
use CommentTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['honeypot', 'node', 'comment', 'contact'];
protected $node;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Set up required Honeypot configuration.
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
$honeypot_config->set('element_name', 'url');
// Enable time_limit protection.
$honeypot_config->set('time_limit', 5);
// Test protecting all forms.
$honeypot_config->set('protect_all_forms', TRUE);
$honeypot_config->set('log', FALSE);
$honeypot_config->save();
// Set up other required configuration.
$user_config = \Drupal::configFactory()->getEditable('user.settings');
$user_config->set('verify_mail', TRUE);
$user_config->set('register', USER_REGISTER_VISITORS);
$user_config->save();
// Create an Article node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
// Create comment field on article.
$this->addDefaultCommentField('node', 'article');
}
}
/**
* Test enabling and disabling of page cache based on time limit settings.
*/
public function testCacheContactForm() {
// Create a Website feedback contact form.
$feedback_form = ContactForm::create([
'id' => 'feedback',
'label' => 'Website feedback',
'recipients' => [],
'reply' => '',
'weight' => 0,
]);
$feedback_form->save();
$contact_settings = \Drupal::configFactory()->getEditable('contact.settings');
$contact_settings->set('default_form', 'feedback')->save();
// Give anonymous users permission to view contact form.
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('access site-wide contact form')
->save();
// Prime the cache.
$this->drupalGet('contact/feedback');
// Test on cache header with time limit enabled, cache should miss.
$this->drupalGet('contact/feedback');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
// Disable time limit.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
// Prime the cache.
$this->drupalGet('contact/feedback');
// Test on cache header with time limit disabled, cache should hit.
$this->drupalGet('contact/feedback');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
// Re-enable the time limit, we should not be seeing the cached version.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
$this->drupalGet('contact/feedback');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
}
/**
* Test enabling and disabling of page cache based on time limit settings.
*/
public function testCacheCommentForm() {
// Set up example node.
$this->node = $this->drupalCreateNode([
'type' => 'article',
'comment' => CommentItemInterface::OPEN,
]);
// Give anonymous users permission to post comments.
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('post comments')
->grantPermission('access comments')
->save();
// Prime the cache.
$this->drupalGet('node/' . $this->node->id());
// Test on cache header with time limit enabled, cache should miss.
$this->drupalGet('node/' . $this->node->id());
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), '', 'Page was not cached.');
// Disable time limit.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
// Prime the cache.
$this->drupalGet('node/' . $this->node->id());
// Test on cache header with time limit disabled, cache should hit.
$this->drupalGet('node/' . $this->node->id());
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
}
}
@@ -0,0 +1,48 @@
<?php
namespace Drupal\honeypot\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Test programmatic submission of forms protected by Honeypot.
*
* @group honeypot
*/
class HoneypotFormProgrammaticSubmissionTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['honeypot', 'honeypot_test', 'user'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Set up required Honeypot configuration.
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
$honeypot_config->set('element_name', 'url');
$honeypot_config->set('time_limit', 5);
$honeypot_config->set('protect_all_forms', TRUE);
$honeypot_config->set('log', FALSE);
$honeypot_config->save();
$this->drupalCreateUser([], 'robo-user');
}
/**
* Trigger a programmatic form submission and verify the validation errors.
*/
public function testProgrammaticFormSubmission() {
$result = $this->drupalGet('/honeypot_test/submit_form');
$form_errors = (array) json_decode($result);
$this->assertNoRaw('There was a problem with your form submission. Please wait 6 seconds and try again.');
$this->assertFalse($form_errors, 'The were no validation errors when submitting the form.');
}
}
@@ -0,0 +1,254 @@
<?php
namespace Drupal\honeypot\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\contact\Entity\ContactForm;
/**
* Test Honeypot spam protection functionality.
*
* @group honeypot
*/
class HoneypotFormTest extends WebTestBase {
use CommentTestTrait;
protected $adminUser;
protected $webUser;
protected $node;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['honeypot', 'node', 'comment', 'contact'];
/**
* Setup before test.
*/
public function setUp() {
// Enable modules required for this test.
parent::setUp();
// Set up required Honeypot configuration.
$honeypot_config = \Drupal::configFactory()->getEditable('honeypot.settings');
$honeypot_config->set('element_name', 'url');
// Disable time_limit protection.
$honeypot_config->set('time_limit', 0);
// Test protecting all forms.
$honeypot_config->set('protect_all_forms', TRUE);
$honeypot_config->set('log', FALSE);
$honeypot_config->save();
// Set up other required configuration.
$user_config = \Drupal::configFactory()->getEditable('user.settings');
$user_config->set('verify_mail', TRUE);
$user_config->set('register', USER_REGISTER_VISITORS);
$user_config->save();
// Create an Article node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
// Create comment field on article.
$this->addDefaultCommentField('node', 'article');
}
// Set up admin user.
$this->adminUser = $this->drupalCreateUser([
'administer honeypot',
'bypass honeypot protection',
'administer content types',
'administer users',
'access comments',
'post comments',
'skip comment approval',
'administer comments',
]);
// Set up web user.
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'create article content',
'access site-wide contact form',
]);
// Set up example node.
$this->node = $this->drupalCreateNode([
'type' => 'article',
'comment' => CommentItemInterface::OPEN,
]);
}
/**
* Make sure user login form is not protected.
*/
public function testUserLoginNotProtected() {
$this->drupalGet('user');
$this->assertNoText('id="edit-url" name="url"', 'Honeypot not enabled on user login form.');
}
/**
* Test user registration (anonymous users).
*/
public function testProtectRegisterUserNormal() {
// Set up form and submit it.
$edit['name'] = $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$this->drupalPostForm('user/register', $edit, t('Create new account'));
// Form should have been submitted successfully.
$this->assertText(t('A welcome message with further instructions has been sent to your email address.'), 'User registered successfully.');
}
/**
* Test for user register honeypot filled.
*/
public function testProtectUserRegisterHoneypotFilled() {
// Set up form and submit it.
$edit['name'] = $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$edit['url'] = 'http://www.example.com/';
$this->drupalPostForm('user/register', $edit, t('Create new account'));
// Form should have error message.
$this->assertText(t('There was a problem with your form submission. Please refresh the page and try again.'), 'Registration form protected by honeypot.');
}
/**
* Test for user register too fast.
*/
public function testProtectRegisterUserTooFast() {
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 1)->save();
// First attempt a submission that does not trigger honeypot.
$edit['name'] = $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$this->drupalGet('user/register');
sleep(2);
$this->drupalPostForm(NULL, $edit, t('Create new account'));
$this->assertNoText(t('There was a problem with your form submission.'));
// Set the time limit a bit higher so we can trigger honeypot.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
// Set up form and submit it.
$edit['name'] = $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$this->drupalPostForm('user/register', $edit, t('Create new account'));
// Form should have error message.
$this->assertText(t('There was a problem with your form submission. Please wait 6 seconds and try again.'), 'Registration form protected by time limit.');
}
/**
* Test comment form protection.
*/
public function testProtectCommentFormNormal() {
$comment = 'Test comment.';
// Disable time limit for honeypot.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 0)->save();
// Log in the web user.
$this->drupalLogin($this->webUser);
// Set up form and submit it.
$edit["comment_body[0][value]"] = $comment;
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertText(t('Your comment has been queued for review'), 'Comment posted successfully.');
}
/**
* Test for comment form honeypot filled.
*/
public function testProtectCommentFormHoneypotFilled() {
$comment = 'Test comment.';
// Log in the web user.
$this->drupalLogin($this->webUser);
// Set up form and submit it.
$edit["comment_body[0][value]"] = $comment;
$edit['url'] = 'http://www.example.com/';
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
$this->assertText(t('There was a problem with your form submission. Please refresh the page and try again.'), 'Comment posted successfully.');
}
/**
* Test for comment form honeypot bypass.
*/
public function testProtectCommentFormHoneypotBypass() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Get the comment reply form and ensure there's no 'url' field.
$this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
$this->assertNoText('id="edit-url" name="url"', 'Honeypot home page field not shown.');
}
/**
* Test node form protection.
*/
public function testProtectNodeFormTooFast() {
// Log in the admin user.
$this->drupalLogin($this->webUser);
// Reset the time limit to 5 seconds.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('time_limit', 5)->save();
// Set up the form and submit it.
$edit["title[0][value]"] = 'Test Page';
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertText(t('There was a problem with your form submission.'), 'Honeypot node form timestamp protection works.');
}
/**
* Test node form protection.
*/
public function testProtectNodeFormPreviewPassthru() {
// Log in the admin user.
$this->drupalLogin($this->webUser);
// Post a node form using the 'Preview' button and make sure it's allowed.
$edit["title[0][value]"] = 'Test Page';
$this->drupalPostForm('node/add/article', $edit, t('Preview'));
$this->assertNoText(t('There was a problem with your form submission.'), 'Honeypot not blocking node form previews.');
}
/**
* Test protection on the Contact form.
*/
public function testProtectContactForm() {
$this->drupalLogin($this->adminUser);
// Disable 'protect_all_forms'.
\Drupal::configFactory()->getEditable('honeypot.settings')->set('protect_all_forms', FALSE)->save();
// Create a Website feedback contact form.
$feedback_form = ContactForm::create([
'id' => 'feedback',
'label' => 'Website feedback',
'recipients' => [],
'reply' => '',
'weight' => 0,
]);
$feedback_form->save();
$contact_settings = \Drupal::configFactory()->getEditable('contact.settings');
$contact_settings->set('default_form', 'feedback')->save();
// Submit the admin form so we can verify the right forms are displayed.
$this->drupalPostForm('admin/config/content/honeypot', [
'form_settings[contact_message_feedback_form]' => TRUE,
], t('Save configuration'));
$this->drupalLogin($this->webUser);
$this->drupalGet('contact/feedback');
$this->assertField('url', 'Honeypot field is added to Contact form.');
}
}