diff --git a/src/EventListener/RequireAuthenticationListener.php b/src/EventListener/RequireAuthenticationListener.php index fa2439d..913719a 100644 --- a/src/EventListener/RequireAuthenticationListener.php +++ b/src/EventListener/RequireAuthenticationListener.php @@ -4,33 +4,52 @@ namespace Terminal42\RootProtectionBundle\EventListener; -use Contao\CoreBundle\DependencyInjection\Attribute\AsHook; -use Contao\CoreBundle\Exception\ResponseException; use Contao\CoreBundle\Framework\ContaoFramework; +use Contao\CoreBundle\Routing\PageFinder; +use Contao\CoreBundle\Routing\ScopeMatcher; +use Contao\CoreBundle\Util\LocaleUtil; use Contao\PageModel; -use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\EventDispatcher\Attribute\AsEventListener; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Event\RequestEvent; -#[AsHook('getPageLayout')] +#[AsEventListener] final class RequireAuthenticationListener { public function __construct( private readonly ContaoFramework $framework, - private readonly RequestStack $requestStack, + private readonly ScopeMatcher $scopeMatcher, + private readonly PageFinder|null $pageFinder = null, ) { } - public function __invoke(PageModel $page): void + public function __invoke(RequestEvent $event): void { - if (null === $request = $this->requestStack->getCurrentRequest()) { + $request = $event->getRequest(); + + if (!$this->scopeMatcher->isFrontendRequest($request)) { return; } $this->framework->initialize(); + // Contao 5.3 + if ($this->pageFinder !== null) { + $rootPage = $this->pageFinder->findRootPageForRequest($request); + } else if (method_exists(PageModel::class, 'findFirstPublishedRootByHostAndLanguage')) { + // Contao 4.13 + /** @var PageModel $pageAdapter */ + $pageAdapter = $this->framework->getAdapter(PageModel::class); + $rootPage = $pageAdapter->findFirstPublishedRootByHostAndLanguage($request->getHost(), [$request->getLocale(), LocaleUtil::getPrimaryLanguage($request->getLocale())]); + } + + if (!isset($rootPage)) { + return; + } + /** @var PageModel $pageAdapter */ $pageAdapter = $this->framework->getAdapter(PageModel::class); - $rootPage = $pageAdapter->findByPk($page->rootId); + $rootPage = $pageAdapter->findByPk($rootPage->id); if (null === $rootPage || !$rootPage->rootProtection) { return; @@ -47,6 +66,7 @@ public function __invoke(PageModel $page): void $response = new Response('401 Authentication Required', Response::HTTP_UNAUTHORIZED); $response->headers->set('WWW-Authenticate', 'Basic realm="Access denied"'); - throw new ResponseException($response); + //throw new ResponseException($response); + $event->setResponse($response); } }