<?php
namespace App\EventSubscriber;
use Firebase\JWT\JWT;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class JwtSseSubscriber implements EventSubscriberInterface
{
public function __construct() {}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'setJwt',
// KernelEvents::TERMINATE : Appelé une seul fois après le traitement de la rêquete, evite les doublons dans la dbb
];
}
public function setJwt(ResponseEvent $event)
{
$response = $event->getResponse();
$dotenv = new Dotenv();
$dotenv->load(__DIR__ . '/../../.env');
$key = $_ENV['MERCURE_JWT_SECRET'];
$head = [
"alg" => "HS256",
"typ" => "JWT"
];
$payload = [
'mercure' => [
// 'subscribe' => [
// $user->getFlux()->getTopicLabel(),
// // 'GLOBALTOPIC',
// // 'http://monsite.fr/message',
// // 'http://monsite.fr/user/'.$this->getUser()->getUsername()
// ],
// 'publish' => [ // publish add also to subcribse
// 'http://monsite.fr/message',
// 'http://monsite.fr/user/'.$this->getUser()->getUsername()
// ],
'subscribe' => [
'*'
],
'publish' => [ // publish add also to subcribse
'*'
],
],
];
$jwt = JWT::encode($payload, $key, 'HS256', null, $head);
// $response = new RedirectResponse('/social', 302);
// $response = $this->forward('App\Controller\HomeController::index', []);
// $response = new Response();
// $response->headers->set('set-cookie', "mercureAuthorization={$jwt}; HttpOnly;");
$response->headers->setCookie(Cookie::create('mercureAuthorization', $jwt));
}
}