src/EventSubscriber/LoginSuspensionCheckSubscriber.php line 69
<?phpdeclare(strict_types=1);namespace App\EventSubscriber;use App\Entity\Students;use App\Security\Exception\StudentSuspendedException;use App\Security\StudentSuspensionChecker;use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;use Lexik\Bundle\JWTAuthenticationBundle\Events;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpKernel\Event\ExceptionEvent;use Symfony\Component\HttpKernel\KernelEvents;/*** Subscriber that blocks suspended students from logging in.* Intercepts the authentication success event BEFORE the JWT token is returned.*/class LoginSuspensionCheckSubscriber implements EventSubscriberInterface{public function __construct(private StudentSuspensionChecker $suspensionChecker) {}public static function getSubscribedEvents(): array{return [Events::AUTHENTICATION_SUCCESS => ['onAuthenticationSuccess', 0],KernelEvents::EXCEPTION => ['onKernelException', 10], // Higher priority to run before other exception handlers];}/*** Called when login credentials are valid, before JWT token is returned.* Blocks suspended students by throwing an exception.*/public function onAuthenticationSuccess(AuthenticationSuccessEvent $event): void{$user = $event->getUser();// Only check for users with associated Person entityif ($user === null || !method_exists($user, 'getPerson') || $user->getPerson() === null) {return;}$person = $user->getPerson();// Only check suspension for Studentsif (!$person instanceof Students) {return;}// Check suspension status$suspensionDetails = $this->suspensionChecker->getSuspensionDetails($person);if ($suspensionDetails['suspended']) {throw new StudentSuspendedException($person->getMatricNo() ?? 'UNKNOWN');}}/*** Handle StudentSuspendedException during login and return 500 response.*/public function onKernelException(ExceptionEvent $event): void{$exception = $event->getThrowable();if (!$exception instanceof StudentSuspendedException) {return;}// Return 500 status code as requested$response = new JsonResponse(['error' => 'Account suspended, contact admin','message' => 'Your account is suspended for this session. Please contact the administrator.'], 500);$event->setResponse($response);}}