<?php declare(strict_types=1);
namespace SwagB2bPlatform\Subscriber;
use Shopware\B2B\Common\Controller\B2bControllerRedirectToLogin;
use Shopware\B2B\StoreFrontAuthentication\Framework\AuthenticationService;
use Shopware\Core\Framework\Routing\KernelListenerPriorities;
use SwagB2bPlatform\Routing\RouteLoader;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use function explode;
class B2bModuleFirewall implements EventSubscriberInterface
{
const ALLOWED_CONTROLLER = [
'b2b_contact.password_activation_controller' => true,
];
/**
* @var AuthenticationService
*/
private $authenticationService;
public function __construct(
AuthenticationService $authenticationService
) {
$this->authenticationService = $authenticationService;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => ['redirectOutOfB2b', KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE_POST],
];
}
public function redirectOutOfB2b(ControllerEvent $event): void
{
if ($this->isAllowedTo($event)) {
return;
}
throw new B2bControllerRedirectToLogin();
}
/**
* @internal
*/
protected function isAllowedTo(ControllerEvent $event): bool
{
if ($this->authenticationService->isB2b() || !$event->getRequest()->attributes->get(RouteLoader::ROUTE_IS_B2B)) {
return true;
}
$routingData = explode('::', $event->getRequest()->get('_controller'));
$isAllowedController = self::ALLOWED_CONTROLLER[$routingData[0]] ?? false;
return (bool) $isAllowedController;
}
}