55namespace PhpList \WebFrontend \EventSubscriber ;
66
77use Symfony \Component \EventDispatcher \EventSubscriberInterface ;
8+ use Symfony \Component \HttpFoundation \RedirectResponse ;
89use Symfony \Component \HttpKernel \Event \ExceptionEvent ;
910use Symfony \Component \HttpKernel \KernelEvents ;
11+ use Symfony \Component \Routing \Generator \UrlGeneratorInterface ;
1012use GuzzleHttp \Exception \ClientException ;
1113
1214class UnauthorizedSubscriber implements EventSubscriberInterface
1315{
16+ private UrlGeneratorInterface $ urlGenerator ;
17+
18+ public function __construct (UrlGeneratorInterface $ urlGenerator )
19+ {
20+ $ this ->urlGenerator = $ urlGenerator ;
21+ }
22+
1423 public static function getSubscribedEvents (): array
1524 {
1625 return [
@@ -23,7 +32,19 @@ public function onKernelException(ExceptionEvent $event): void
2332 $ exception = $ event ->getThrowable ();
2433
2534 if ($ exception instanceof ClientException && $ exception ->getCode () === 401 ) {
26- // Redirect to login page or handle unauthorized access
35+ $ request = $ event ->getRequest ();
36+ $ session = $ request ->getSession ();
37+
38+ if ($ session ->has ('auth_token ' )) {
39+ $ session ->remove ('auth_token ' );
40+ }
41+
42+ $ session ->set ('login_error ' , 'Your session has expired. Please log in again. ' );
43+
44+ $ loginUrl = $ this ->urlGenerator ->generate ('login ' );
45+ $ response = new RedirectResponse ($ loginUrl );
46+
47+ $ event ->setResponse ($ response );
2748 }
2849 }
2950}
0 commit comments