<?php
declare(strict_types=1);
namespace App\Bundle\Croatia\EventListener;
use EightPoints\Bundle\GuzzleBundle\Events\GuzzleEventListenerInterface;
use EightPoints\Bundle\GuzzleBundle\Events\PreTransactionEvent;
use GuzzleHttp\Client;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProvider\JWSProviderInterface;
use Psr\Cache\CacheItemPoolInterface;
class GenticsMeshApiAuthListener implements GuzzleEventListenerInterface
{
/**
* @var string
*/
protected $serviceName;
/**
* @var CacheItemPoolInterface
*/
protected $cache;
/**
* @var Client
*/
protected $client;
/**
* @var JWSProviderInterface
*/
protected $JWSProvider;
public function __construct(CacheItemPoolInterface $cache, Client $client, JWSProviderInterface $JWSProvider)
{
$this->cache = $cache;
$this->client = $client;
$this->JWSProvider = $JWSProvider;
}
public function getServiceName()
{
return $this->serviceName;
}
/**
* @inheritDoc
*/
public function setServiceName($serviceName)
{
$this->serviceName = $serviceName;
return $this;
}
/**
* @return string
* @throws \Psr\Cache\InvalidArgumentException
*/
protected function getToken(): string
{
$cacheItem = $this->cache->getItem('gentics_mesh_token');
if ($cacheItem->isHit()) {
$token = $cacheItem->get();
return $token['token'];
}
$body = [
'username' => getenv('GETMESH_USER'),
'password' => getenv('GETMESH_PASSWORD')
];
$response = $this->client->post('/api/v1/auth/login', ['body' => json_encode($body)]);
$token = json_decode($response->getBody()->getContents(), true);
$payload = $this->JWSProvider->load($token['token'])->getPayload();
$expiresAt = (new \DateTimeImmutable())->setTimestamp($payload['exp']);
$cacheItem->expiresAt($expiresAt);
$cacheItem->set($token);
$this->cache->save($cacheItem);
return $token['token'];
}
/**
* @param PreTransactionEvent $event
*
* @throws \Psr\Cache\InvalidArgumentException
*/
public function onPreTransaction(PreTransactionEvent $event)
{
if ($event->getServiceName() !== $this->getServiceName()) {
return;
}
$token = $this->getToken();
$request = $event->getTransaction();
$modifiedRequest = $request->withHeader('Authorization', sprintf('Bearer %s', $token));
$event->setTransaction($modifiedRequest);
}
}