1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Netgen\Bundle\SiteAccessRoutesBundle\EventListener; |
6
|
|
|
|
7
|
|
|
use eZ\Publish\Core\MVC\Symfony\SiteAccess; |
8
|
|
|
use Netgen\Bundle\SiteAccessRoutesBundle\Matcher\MatcherInterface; |
9
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
10
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
11
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
12
|
|
|
use Symfony\Component\HttpKernel\HttpKernelInterface; |
13
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
14
|
|
|
use function is_array; |
15
|
|
|
|
16
|
|
|
final class RequestListener implements EventSubscriberInterface |
17
|
|
|
{ |
18
|
|
|
public const ALLOWED_SITEACCESSES_KEY = 'allowed_siteaccess'; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var \Netgen\Bundle\SiteAccessRoutesBundle\Matcher\MatcherInterface |
22
|
|
|
*/ |
23
|
|
|
private $matcher; |
24
|
|
|
|
25
|
|
|
public function __construct(MatcherInterface $matcher) |
26
|
|
|
{ |
27
|
|
|
$this->matcher = $matcher; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function getSubscribedEvents(): array |
31
|
|
|
{ |
32
|
|
|
return [ |
33
|
|
|
// Needs to execute right after Symfony RouterListener (priority of 32) |
34
|
|
|
KernelEvents::REQUEST => ['onKernelRequest', 31], |
35
|
|
|
]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Throws an exception if current route is not allowed in current siteaccess. |
40
|
|
|
*/ |
41
|
|
|
public function onKernelRequest(RequestEvent $event): void |
42
|
|
|
{ |
43
|
|
|
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { |
44
|
|
|
return; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$requestAttributes = $event->getRequest()->attributes; |
48
|
|
|
|
49
|
|
|
$currentSiteAccess = $requestAttributes->get('siteaccess'); |
50
|
|
|
$allowedSiteAccesses = $requestAttributes->get(self::ALLOWED_SITEACCESSES_KEY); |
51
|
|
|
|
52
|
|
|
// We allow the route if no current siteaccess is set or |
53
|
|
|
// no allowed siteaccesses (meaning all are allowed) are defined |
54
|
|
|
if (!$currentSiteAccess instanceof SiteAccess || empty($allowedSiteAccesses)) { |
55
|
|
|
return; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (!is_array($allowedSiteAccesses)) { |
59
|
|
|
$allowedSiteAccesses = [$allowedSiteAccesses]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if ($this->matcher->isAllowed($currentSiteAccess->name, $allowedSiteAccesses)) { |
63
|
|
|
return; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
throw new NotFoundHttpException('Route is not allowed in current siteaccess'); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|