Skip to content

Commit

Permalink
Use the request event instead of the hook, so we can address custom c…
Browse files Browse the repository at this point in the history
…ontrollers as well (e.g. sitemap controller)
  • Loading branch information
qzminski committed Dec 13, 2024
1 parent 1b470d5 commit 8d647d2
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions src/EventListener/RequireAuthenticationListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
}
}

0 comments on commit 8d647d2

Please sign in to comment.