<?php
namespace App\AppBundle\EventListener;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class InactivityResponseListener
{
protected $jwtEncoder;
protected $inactivityTTL;
public function __construct(JWTEncoderInterface $encoder, $inactivityTTL)
{
$this->jwtEncoder = $encoder;
$this->inactivityTTL = $inactivityTTL;
}
public function onKernelResponse(ResponseEvent $event)
{
// Get current response from event
$response = $event->getResponse();
// If not an error, set Authorization header with the latest auth token
if ($response !== null) {
if ($response->getStatusCode() < 400) {
$request = $event->getRequest();
// Avoid updating the inactivity_exp and returning the 'Authorization' header
// if the request explicitly has the 'doNotCountAsActivity' flag set to true
if (
empty($request->get('doNotCountAsActivity')) ||
$request->get('doNotCountAsActivity') != 'true'
) {
// Decode original token from request (although this should be done from
// the token stored from the original decodification. Couldn't make it work)
$authenticationToken = str_replace('Bearer ', '',
$request->headers->get('Authorization'));
try {
$payload = $this->jwtEncoder->decode($authenticationToken);
// Update timestamp
$payload['inactivity_exp'] = time() + $this->inactivityTTL;
// Set authentication header with updated token
$response->headers->set('Authorization',
$this->jwtEncoder->encode($payload));
} catch (JWTDecodeFailureException $e) {
// No action
}
}
} else {
// Remove header on errors (it might have been set by a call to this
// listener before the response code was set to an error one)
$response->headers->remove('Authorization');
}
}
}
}