5
5
namespace PhpList \WebFrontend \EventSubscriber ;
6
6
7
7
use Symfony \Component \EventDispatcher \EventSubscriberInterface ;
8
+ use Symfony \Component \HttpFoundation \RedirectResponse ;
8
9
use Symfony \Component \HttpKernel \Event \ExceptionEvent ;
9
10
use Symfony \Component \HttpKernel \KernelEvents ;
11
+ use Symfony \Component \Routing \Generator \UrlGeneratorInterface ;
10
12
use GuzzleHttp \Exception \ClientException ;
11
13
12
14
class UnauthorizedSubscriber implements EventSubscriberInterface
13
15
{
16
+ private UrlGeneratorInterface $ urlGenerator ;
17
+
18
+ public function __construct (UrlGeneratorInterface $ urlGenerator )
19
+ {
20
+ $ this ->urlGenerator = $ urlGenerator ;
21
+ }
22
+
14
23
public static function getSubscribedEvents (): array
15
24
{
16
25
return [
@@ -23,7 +32,19 @@ public function onKernelException(ExceptionEvent $event): void
23
32
$ exception = $ event ->getThrowable ();
24
33
25
34
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 );
27
48
}
28
49
}
29
50
}
0 commit comments