2

I'm new to Symfony. I use LexicJWT token.

final class ProductCreateSubscriber implements EventSubscriberInterface
{
    private $entityManager;
    private $hostRepository;

    public function __construct(EntityManagerInterface $entityManager, HostRepository $hostRepository)
    {
        $this->entityManager = $entityManager;
        $this->hostRepository = $hostRepository;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['createHost', EventPriorities::PRE_WRITE],
        ];
    }

    public function createHost(GetResponseForControllerResultEvent $event)
    {
        $product = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        - - - - - -- - - I NEED USER HERE - - - - -  - -    

        if (!$product instanceof Product || Request::METHOD_POST !== $method) {
            return;
        } 

        $parsedUrl = parse_url($product->getUrl());
        if (isset($parsedUrl['host'])) {
            $host = $this->hostRepository->findOneByName($parsedUrl['host']);
            if (!$host) {
                $host = $this->hostRepository->createByName($parsedUrl['host']);
            }
            $product->setHost($host);
        }
    }
}

How can i get User in createHost method? How can I get a user or token in EventSubsriber? Can't find any info on this? Where can I read about it?

Billizzard
  • 472
  • 6
  • 15

1 Answers1

2

JWT token is passed through the header, so you need to access header in event.

You can try to access header like that:

$request = $event->getRequest();
$headers = $request->headers->all();

From the header you can take the Authentication header that has JWT token inside, and the decode it to get user.

UPDATE: As @Jared Farrish mentioned make sure that token is valid!

nicandr
  • 341
  • 2
  • 8
  • 2
    @Billizzard Make sure to validate the signature before trusting what it contains. You might also consider [Javascript Object Signing and Encryption (JOSE)](https://jose.readthedocs.io/en/latest/). – Jared Farrish Dec 14 '18 at 14:32