|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpList\WebFrontend\EventSubscriber; |
| 6 | + |
| 7 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 8 | +use Symfony\Component\HttpFoundation\RedirectResponse; |
| 9 | +use Symfony\Component\HttpFoundation\Request; |
| 10 | +use Symfony\Component\HttpKernel\Event\RequestEvent; |
| 11 | +use Symfony\Component\HttpKernel\KernelEvents; |
| 12 | +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
| 13 | + |
| 14 | +/** |
| 15 | + * Temporary auth gate until Symfony SecurityBundle is active at runtime. |
| 16 | + * |
| 17 | + * Redirects all anonymous requests to the login page, except explicitly public paths. |
| 18 | + */ |
| 19 | +class AuthGateSubscriber implements EventSubscriberInterface |
| 20 | +{ |
| 21 | + public function __construct(private readonly UrlGeneratorInterface $urlGenerator) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + public static function getSubscribedEvents(): array |
| 26 | + { |
| 27 | + // Run early in the request, after routing is available is not required here |
| 28 | + return [ |
| 29 | + KernelEvents::REQUEST => ['onKernelRequest', 8], |
| 30 | + ]; |
| 31 | + } |
| 32 | + |
| 33 | + public function onKernelRequest(RequestEvent $event): void |
| 34 | + { |
| 35 | + if (!$event->isMainRequest()) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + $request = $event->getRequest(); |
| 40 | + if ($this->isPublicPath($request)) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + $session = $request->getSession(); |
| 45 | + if (!$session || !$session->has('auth_token')) { |
| 46 | + $loginUrl = $this->urlGenerator->generate('login'); |
| 47 | + $event->setResponse(new RedirectResponse($loginUrl)); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private function isPublicPath(Request $request): bool |
| 52 | + { |
| 53 | + $path = $request->getPathInfo() ?? '/'; |
| 54 | + |
| 55 | + // Public login route |
| 56 | + if ($path === '/login' || str_starts_with($path, '/login')) { |
| 57 | + return true; |
| 58 | + } |
| 59 | + |
| 60 | + // Allow Symfony debug/profiler and WDT if present |
| 61 | + if (str_starts_with($path, '/_profiler') || str_starts_with($path, '/_wdt')) { |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + // Allow static assets commonly served under these prefixes |
| 66 | + foreach (['/build/', '/assets/', '/css/', '/js/', '/images/', '/img/', '/favicon', '/robots.txt'] as $prefix) { |
| 67 | + if (str_starts_with($path, $prefix)) { |
| 68 | + return true; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return false; |
| 73 | + } |
| 74 | +} |
0 commit comments