I want to add a session cookie when a user logs in.
The previous implementation I had, was setting the cookie in hook_user_login
with this snippet:
$response = new Response();
$response->headers->setCookie($plain_cookie);
$response->send();
But this was causing randomly the following exception:
RuntimeException: Failed to start the session because headers have already been sent
After some research, I found out that a way to handle it is via an EventSubscriber. https://www.drupal.org/docs/develop/creating-modules/subscribe-to-and-dispatch-events
However, I have not managed to dispatch a ResponseEvent in order to add the cookie to the response header, aka. the cookie is not being added after login. I have tried event low priorities in order for the event to be exeuted at the end, but again it does not work.
function custom_user_login($account) {
$response = new Response();
$event = new MyResponseEvent($response);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, MyResponseEvent::EVENT_NAME);
}
And in my EventSubscriber:
public function onUserLogin(MyResponseEvent $event) {
$response = $event->getResponse();
$response->headers->setCookie($plain_cookie);
$event->setResponse($response);
}
How could I do it?