<?php
namespace App\Security\Firewall;
use Products\NotificationsBundle\Controller\AbstractPortalController;
use Products\NotificationsBundle\Controller\Portal\LoginController;
use Products\NotificationsBundle\Controller\Portal\MessagesController;
use Products\NotificationsBundle\Controller\Portal\OptInController;
use Products\NotificationsBundle\Entity\Profile;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
/**
* Class PortalFirewall
* @package App\Security\Firewall
*/
final readonly class PortalFirewall implements
RequestMatcherInterface,
AuthenticationEntryPointInterface,
EventSubscriberInterface
{
public function __construct(
private RouterInterface $router,
private Security $security,
)
{
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents(): array
{
return [
ControllerEvent::class => 'onController',
];
}
/**
* @param ControllerEvent $event
* @return void
*/
public function onController(
ControllerEvent $event,
): void
{
$controller = $event->getController();
if (is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof AbstractPortalController && $this->matches($event->getRequest()) && ! $this->security->getUser() instanceof Profile) {
throw new AuthenticationException();
}
}
/**
* {@inheritDoc}
*/
public function matches(
Request $request,
): bool
{
$route = $request->attributes->get('_route');
if ( ! empty($route) && str_starts_with($route, 'app.notifications.portal.')) {
switch (true) {
case $route === LoginController::ROUTES__LOGIN:
case $route === LoginController::ROUTES__UNMATCHED:
case $route === LoginController::ROUTES__CODE:
case $route === LoginController::ROUTES__SELECT:
case $route === MessagesController::ROUTES__MAIN:
case $route === MessagesController::ROUTES__DETAILS:
case $route === MessagesController::ROUTES__CONTACT:
case $route === MessagesController::ROUTES__MESSAGE_HTML:
case $route === OptInController::ROUTES__MAIN:
case $route === OptInController::ROUTES__NOTICE:
case $route === OptInController::ROUTES__PRIVACY_POLICY:
return false;
default:
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public function start(
Request $request,
?AuthenticationException $authException = null,
): RedirectResponse
{
return new RedirectResponse(
$this->router->generate(
LoginController::ROUTES__LOGIN,
),
);
}
}