src/AppBundle/EventListener/InactivityResponseListener.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\AppBundle\EventListener;
  3. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
  5. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  6. class InactivityResponseListener
  7. {
  8.     protected $jwtEncoder;
  9.     protected $inactivityTTL;
  10.     public function __construct(JWTEncoderInterface $encoder$inactivityTTL)
  11.     {
  12.         $this->jwtEncoder $encoder;
  13.         $this->inactivityTTL $inactivityTTL;
  14.     }
  15.     public function onKernelResponse(ResponseEvent $event)
  16.     {
  17.         // Get current response from event
  18.         $response $event->getResponse();
  19.         // If not an error, set Authorization header with the latest auth token
  20.         if ($response !== null) {
  21.             if ($response->getStatusCode() < 400) {
  22.                 $request $event->getRequest();
  23.                 // Avoid updating the inactivity_exp and returning the 'Authorization' header
  24.                 // if the request explicitly has the 'doNotCountAsActivity' flag set to true
  25.                 if (
  26.                     empty($request->get('doNotCountAsActivity')) ||
  27.                     $request->get('doNotCountAsActivity') != 'true'
  28.                 ) {
  29.                     // Decode original token from request (although this should be done from
  30.                     // the token stored from the original decodification. Couldn't make it work)
  31.                     $authenticationToken str_replace('Bearer ''',
  32.                         $request->headers->get('Authorization'));
  33.                     try {
  34.                         $payload $this->jwtEncoder->decode($authenticationToken);
  35.                         // Update timestamp
  36.                         $payload['inactivity_exp'] = time() + $this->inactivityTTL;
  37.                         // Set authentication header with updated token
  38.                         $response->headers->set('Authorization',
  39.                             $this->jwtEncoder->encode($payload));
  40.                     } catch (JWTDecodeFailureException $e) {
  41.                         // No action
  42.                     }
  43.                 }
  44.             } else {
  45.                 // Remove header on errors (it might have been set by a call to this 
  46.                 // listener before the response code was set to an error one)
  47.                 $response->headers->remove('Authorization');
  48.             }
  49.         }
  50.     }
  51. }