Skip to content

Commit 9bc0056

Browse files
committed
ISSUE-345: UnauthorizedSubscriber
1 parent 6dd9352 commit 9bc0056

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/Controller/AuthController.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ public function login(Request $request): Response
2929
}
3030

3131
$error = null;
32+
$session = $request->getSession();
33+
if ($session->has('login_error')) {
34+
$error = $session->get('login_error');
35+
$session->remove('login_error');
36+
}
3237

3338
if ($request->isMethod('POST')) {
3439
$username = $request->request->get('username');

src/EventSubscriber/UnauthorizedSubscriber.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,21 @@
55
namespace PhpList\WebFrontend\EventSubscriber;
66

77
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8+
use Symfony\Component\HttpFoundation\RedirectResponse;
89
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
910
use Symfony\Component\HttpKernel\KernelEvents;
11+
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
1012
use GuzzleHttp\Exception\ClientException;
1113

1214
class 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

Comments
 (0)