src/Front/Security/Authentication/CustomerAuthenticationSubscriber.php line 53
<?php
namespace App\Front\Security\Authentication;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpFoundation\JsonResponse,
Symfony\Component\Security\Http\Event\LoginFailureEvent,
Symfony\Component\Security\Http\Event\LoginSuccessEvent,
Symfony\Component\Security\Http\Event\LogoutEvent;
use App\Front\Exception\FrontApiException;
final class CustomerAuthenticationSubscriber implements EventSubscriberInterface
{
private const REQUEST_FIREWALL_CONTEXT_ATTRIBUTE = '_firewall_context';
private const CUSTOMER_FIREWALL_NAME = 'customer';
public static function getSubscribedEvents() : array
{
return [
LoginSuccessEvent::class => [
['onLoginSuccess', 10],
],
LoginFailureEvent::class => [
['onLoginFailure', 10],
],
LogoutEvent::class => [
['onLogout', 10]
]
];
}
public function onLoginSuccess(LoginSuccessEvent $event): void
{
if (! $this->isEventCustomerFirewall($event) || ! $this->isOnlyJsonAcceptable($event->getRequest())) {
return;
}
$event->setResponse(new JsonResponse([
'message' => 'success'
]));
}
public function onLoginFailure(LoginFailureEvent $event): void
{
if (! $this->isEventCustomerFirewall($event) || ! $this->isOnlyJsonAcceptable($event->getRequest())) {
return;
}
throw new FrontApiException(401, $event->getException()->getMessage());
}
public function onLogout(LogoutEvent $event): void
{
$request = $event->getRequest();
if (! $this->isRequestCustomerFirewall($request) || ! $this->isOnlyJsonAcceptable($request)) {
return;
}
$event->setResponse(new JsonResponse([
'message' => 'success'
]));
}
private function getFirewallName(Request $request): ?string
{
if (! $context = $request->attributes->get(self::REQUEST_FIREWALL_CONTEXT_ATTRIBUTE)) {
return null;
}
$contextPath = explode('.', $context);
return end($contextPath);
}
private function isEventCustomerFirewall(LoginFailureEvent|LoginSuccessEvent $event): bool
{
return $event->getFirewallName() === self::CUSTOMER_FIREWALL_NAME;
}
private function isRequestCustomerFirewall(Request $request): bool
{
return $this->getFirewallName($request) === self::CUSTOMER_FIREWALL_NAME;
}
private function isOnlyJsonAcceptable(Request $request): bool
{
$acceptableTypes = $request->getAcceptableContentTypes();
return count($acceptableTypes) === 1 && $acceptableTypes[0] === 'application/json';
}
}