Easy_solution/src/Controller/MercureController.php

49 lines
1.5 KiB
PHP

<?php
namespace App\Controller;
use App\Service\UserService;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
class MercureController extends AbstractController
{
public function __construct(private readonly UserService $userService)
{
}
#[Route(path: '/mercure-token', name: 'mercure_token', methods: ['GET'])]
public function getMercureToken(Request $request): JsonResponse
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->userService->getUserByIdentifier($this->getUser()->getUserIdentifier());
$domain = $request->getSchemeAndHttpHost();
$topic = sprintf('%s/notifications/user/%d', $domain, $user->getId());
// Generate JWT token for Mercure subscription
$secret = $this->getParameter('mercure_secret');
$config = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::plainText($secret)
);
$token = $config->builder()
->withClaim('mercure', [
'subscribe' => [$topic]
])
->getToken($config->signer(), $config->signingKey());
return new JsonResponse([
'token' => $token->toString(),
'topic' => $topic,
'userId' => $user->getId(),
]);
}
}