Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented cookie protection for Symfony 3 too #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ public function getConfigTreeBuilder()
->defaultValue('Form fields are invalid')->end()
->end()
->end()


->arrayNode('cookie')
->canBeDisabled()
->children()
->scalarNode('name')->defaultValue('antispam')->end()
->booleanNode('global')->defaultFalse()->end()
->scalarNode('message')
->defaultValue('Something is wrong, please try again')->end()
->end()
->end()
->end();

return $treeBuilder;
Expand Down
17 changes: 17 additions & 0 deletions DependencyInjection/IsometriksSpamExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public function load(array $configs, ContainerBuilder $container)

$this->processTimedConfig($config['timed'], $container, $loader);
$this->processHoneypotConfig($config['honeypot'], $container, $loader);
$this->processCookieConfig($config['cookie'], $container, $loader);
}

private function processTimedConfig(array $config, ContainerBuilder $container, XmlFileLoader $loader)
Expand Down Expand Up @@ -61,4 +62,20 @@ private function processHoneypotConfig(array $config, ContainerBuilder $containe
'message' => $config['message'],
));
}

private function processCookieConfig(array $config, ContainerBuilder $container, XmlFileLoader $loader)
{
if (!$this->isConfigEnabled($container, $config)) {
return;
}

$loader->load('cookie.xml');

$definition = $container->getDefinition('isometriks_spam.form.extension.type.cookie');
$definition->addArgument(array(
'name' => $config['name'],
'global' => $config['global'],
'message' => $config['message'],
));
}
}
35 changes: 35 additions & 0 deletions EventListener/KernelResponseListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php


namespace Isometriks\Bundle\SpamBundle\EventListener;

use Isometriks\Bundle\SpamBundle\Form\Extension\Spam\Provider\CookieProvider;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class KernelResponseListener
{
/** @var CookieProvider */
private $cookieProvider;

public function __construct($cookieProvider)
{
$this->cookieProvider = $cookieProvider;
}

public function onKernelResponse(FilterResponseEvent $responseEvent)
{
$cookieData = $this->cookieProvider->getCookieSettings();
if ($cookieData) {
if($cookieData['mode'] == 'add') {
$cookie = new Cookie($cookieData['name'], 1);

$responseEvent->getResponse()->headers->setCookie($cookie);
} else if ($cookieData['mode'] == 'remove') {
$responseEvent->getResponse()->headers->removeCookie($cookieData['name']);
$responseEvent->getResponse()->headers->clearCookie($cookieData['name']);
$this->cookieProvider->removeCookieSettings();
}
}
}
}
64 changes: 64 additions & 0 deletions Form/Extension/Spam/EventListener/CookieValidationListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php


namespace Isometriks\Bundle\SpamBundle\Form\Extension\Spam\EventListener;

use Isometriks\Bundle\SpamBundle\Form\Extension\Spam\Provider\CookieProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\TranslatorInterface;

class CookieValidationListener implements EventSubscriberInterface
{
private $cookieProvider;
private $request;
private $translator;
private $translationDomain;
private $cookieName;
private $errorMessage;

public function __construct(CookieProvider $cookieProvider,
Request $request,
TranslatorInterface $translator,
$translationDomain,
$cookieName,
$errorMessage)
{
$this->cookieProvider = $cookieProvider;
$this->request = $request;
$this->translator = $translator;
$this->translationDomain = $translationDomain;
$this->cookieName = $cookieName;
$this->errorMessage = $errorMessage;
}

public function preSubmit(FormEvent $event)
{
$form = $event->getForm();

if($form->isRoot() && $form->getConfig()->getOption('compound') && !$this->request->cookies->get($this->cookieName)) {
$errorMessage = $this->errorMessage;

if (null !== $this->translator) {
$errorMessage = $this->translator->trans($errorMessage, array(), $this->translationDomain);
}

$form->addError(new FormError($errorMessage));

return;
}

$this->cookieProvider->removeAntispamCookie($this->cookieName);
}


public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SUBMIT => 'preSubmit',
);
}
}
36 changes: 36 additions & 0 deletions Form/Extension/Spam/Provider/CookieProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php


namespace Isometriks\Bundle\SpamBundle\Form\Extension\Spam\Provider;

use Symfony\Component\HttpFoundation\Session\Session;

class CookieProvider
{
private $session;

public function __construct(Session $session)
{
$this->session = $session;
}

public function setAntispamCookie($cookieName)
{
$this->session->set('antispam_cookie', array('mode' => 'add', 'name' => $cookieName));
}

public function removeAntispamCookie($cookieName)
{
$this->session->set('antispam_cookie', array('mode' => 'remove', 'name' => $cookieName));
}

public function getCookieSettings()
{
return $this->session->get('antispam_cookie');
}

public function removeCookieSettings()
{
$this->session->remove('antispam_cookie');
}
}
83 changes: 83 additions & 0 deletions Form/Extension/Spam/Type/FormTypeCookieExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php


namespace Isometriks\Bundle\SpamBundle\Form\Extension\Spam\Type;

use Isometriks\Bundle\SpamBundle\Form\Extension\Spam\EventListener\CookieValidationListener;
use Isometriks\Bundle\SpamBundle\Form\Extension\Spam\Provider\CookieProvider;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;

class FormTypeCookieExtension extends AbstractTypeExtension
{
private $cookieProvider;
private $request;
private $session;
private $translator;
private $translationDomain;
private $defaults;

public function __construct(
CookieProvider $cookieProvider,
RequestStack $requestStack,
Session $session,
TranslatorInterface $translator,
$translationDomain,
array $defaults
) {
$this->cookieProvider = $cookieProvider;
$this->request = $requestStack->getCurrentRequest();
$this->session = $session;
$this->translator = $translator;
$this->translationDomain = $translationDomain;
$this->defaults = $defaults;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['cookie']) {
return;
}

$builder
->addEventSubscriber(new CookieValidationListener(
$this->cookieProvider,
$this->request,
$this->translator,
$this->translationDomain,
$options['cookie_name'],
$options['cookie_message']
));
}

public function finishView(FormView $view, FormInterface $form, array $options)
{
$this->cookieProvider->setAntispamCookie($options['cookie_name']);
}

public function setDefaultOptions(OptionsResolver $resolver)
{
$this->configureOptions($resolver);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'cookie' => $this->defaults['global'],
'cookie_name' => $this->defaults['name'],
'cookie_message' => $this->defaults['message'],
));
}

public function getExtendedType()
{
return FormType::class;
}
}
12 changes: 6 additions & 6 deletions Form/Extension/Spam/Type/FormTypeHoneypotExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Translation\TranslatorInterface;

class FormTypeHoneypotExtension extends AbstractTypeExtension
Expand All @@ -19,10 +18,11 @@ class FormTypeHoneypotExtension extends AbstractTypeExtension
private $translationDomain;
private $defaults;

public function __construct(TranslatorInterface $translator,
$translationDomain,
array $defaults)
{
public function __construct(
TranslatorInterface $translator,
$translationDomain,
array $defaults
) {
$this->translator = $translator;
$this->translationDomain = $translationDomain;
$this->defaults = $defaults;
Expand Down Expand Up @@ -74,7 +74,7 @@ public function finishView(FormView $view, FormInterface $form, array $options)
}
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolver $resolver)
{
$this->configureOptions($resolver);
}
Expand Down
13 changes: 7 additions & 6 deletions Form/Extension/Spam/Type/FormTypeTimedSpamExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ class FormTypeTimedSpamExtension extends AbstractTypeExtension
private $translationDomain;
private $defaults;

public function __construct(TimedSpamProviderInterface $timeProvider,
TranslatorInterface $translator,
$translationDomain,
array $defaults)
{
public function __construct(
TimedSpamProviderInterface $timeProvider,
TranslatorInterface $translator,
$translationDomain,
array $defaults
) {
$this->timeProvider = $timeProvider;
$this->translator = $translator;
$this->translationDomain = $translationDomain;
Expand Down Expand Up @@ -59,7 +60,7 @@ public function finishView(FormView $view, FormInterface $form, array $options)
}
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolver $resolver)
{
$this->configureOptions($resolver);
}
Expand Down
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ If the field is filled out, then the form is invalid. You can optionally
choose to use a class name to hide the form element as well in case the
bot tries to check the style attribute.

```yml
```YAML
isometriks_spam:
honeypot:
field: email_address
Expand Down Expand Up @@ -123,9 +123,38 @@ public function configureOptions(OptionsResolver $resolver)
}
```

### Twig Form Error message rendering
### Cookie Spam Prevention

Most of spam bots can't use cookies so we could check cookie value on each request.

If there is no cookie set - then the request is invalid and set by bots.
These cookies are not used for any tracking and are deleted after form is submitted and handled.

Configuration:

```YAML
isometriks_spam:
cookie:
name: antispam_cookie
global: false
message: Something is wrong, please try again
```

Usage:

```php
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'cookie' => true,
// ...
));
}
```

### Twig Form Error message rendering

```twig
{% if form.vars.errors is not empty %}
<div class="alert alert-danger has-error">{{ form_errors(form) }}</div>
{% endif %}
Expand Down
Loading