I am trying to implement a way to stop Symfony 2 creating a cookie. When a user logs onto the clients site a popup will appear which will allow the user to accept the cookie policy. Only after this has been accepted should cookies be created. How do I stop symfony creating cookies until this has happened?
I think the best way is to check user upon login.
One option is to have kernel.event_listener
It should be something like this
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
/**
* This listener ensure that logged user must accept latest terms of service
*
* @author po_taka
*/
class TermsForceListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$user = $this->tokenStorage->getToken()->getUser();
if (!$user instanceof YOUR_CLASS_HERE) {
return;
}
if ($user->getTermsAccepted()) {
// terms are accepted, continue with the page loading
return;
}
if (YOUR_VALIDATION_IF_CURRENT_PAGE_IS_TERMS_ACEEPTING_PAGE) {
$response = new \Symfony\Component\HttpFoundation\RedirectResponse(TERMS_ACCEPTING_PAGE, 302);
$event->setResponse($response);
$event->stopPropagation();
}
}
}
You can register it using the following yaml
YOUR_SEVICE_NAME_HERE:
class: TermsForceListener
arguments: ['@security.token_storage']
tags:
- { name: kernel.event_listener, event: kernel.request }
You can read more about symfony events here - https://symfony.com/doc/current/reference/events.html