<?php declare(strict_types=1);
namespace Samson\Api\Soap\Subscriber;
/***
*
* This file is part of the "SAMSON Shop" project.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2020
*
***/
use Samson\Api\Soap\Controller\ApiController;
use Samson\Api\Soap\Service\AuthService;
use Samson\Service\LoggerService;
use Shopware\Core\Framework\Routing\KernelListenerPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* Class AuthSubscriber
* @package Samson\Api\BasicAuth
* @author Artur Seitz <artur.seitz@dkd.de>
*/
class AuthSubscriber implements EventSubscriberInterface
{
protected AuthService $authService;
protected LoggerService $logger;
/**
* AuthSubscriber constructor.
*
* @param AuthService $authService
* @param LoggerService $logger
*/
public function __construct(
AuthService $authService,
LoggerService $logger
) {
$this->authService = $authService;
$this->logger = $logger;
}
/** {@inheritDoc} */
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => [
['resolveContext', KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_PRIORITY_AUTH_VALIDATE],
],
];
}
/**
* KernelEvents::CONTROLLER event listener.
*
* @param ControllerEvent $event
*/
public function resolveContext(ControllerEvent $event): void
{
$controller = $event->getController();
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof ApiController) {
if (!$event->getRequest()->headers->has('Authorization')) {
throw new UnauthorizedHttpException('header', 'Header "Authorization" is required.');
}
if (!$this->authService->isAuthenticated($event->getRequest())) {
$this->logger->authenticationFailed($event->getRequest());
throw new AuthenticationException('Basic authorization failed. The user is unknown.');
}
}
}
}