<?php
namespace App\EventSubscriber;
use App\Entity\Organization;
use App\Entity\User;
use Doctrine\Common\Collections\Collection;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
use Symfony\Component\HttpFoundation\Response;
class JWTSubsciber
{
public function onJWTCreated(JWTCreatedEvent $event)
{
$data = $event->getData();
$user = $event->getUser();
if (!$user instanceof User) {
return;
}
/** @var Collection $organizations */
$organizations = $user->getOrganizations();
if ($organizations->count() > 0) {
/** @var Organization $organization */
$organization = $organizations->first();
$data['organization_id'] = $organization->getId();
$event->setData($data);
}
}
public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
{
$data = [
'code' => 'authenticationFailure',
'detail' => 'Bad credentials, please verify that your username/password are correctly set',
'status' => Response::HTTP_UNPROCESSABLE_ENTITY,
'title' => 'Unauthorized',
'errors' => [],
];
$response = new Response(
json_encode($data),
Response::HTTP_UNPROCESSABLE_ENTITY
);
$response->headers->set('Content-Type', 'application/json');
$event->setResponse($response);
}
public function onJWTInvalid(JWTInvalidEvent $event)
{
$data = [
'code' => 'invalidJWT',
'detail' => 'Your token is invalid, please login again to get a new one',
'status' => Response::HTTP_UNAUTHORIZED,
'title' => 'Forbidden',
'errors' => [],
];
$response = new Response(
json_encode($data),
Response::HTTP_UNAUTHORIZED
);
$response->headers->set('Content-Type', 'application/json');
$event->setResponse($response);
}
public function onJWTNotFound(JWTNotFoundEvent $event)
{
$data = [
'code' => 'missingJWT',
'detail' => 'Missing token',
'status' => Response::HTTP_UNAUTHORIZED,
'title' => 'Forbidden',
'errors' => [],
];
$response = new Response(
json_encode($data),
Response::HTTP_UNAUTHORIZED
);
$response->headers->set('Content-Type', 'application/json');
$event->setResponse($response);
}
public function onJWTExpired(JWTExpiredEvent $event)
{
$data = [
'code' => 'expiredJWT',
'detail' => 'Your token is expired, please renew it',
'status' => Response::HTTP_UNAUTHORIZED,
'title' => 'Forbidden',
'errors' => [],
];
$response = new Response(
json_encode($data),
Response::HTTP_UNAUTHORIZED
);
$response->headers->set('Content-Type', 'application/json');
$event->setResponse($response);
}
}