<?php
namespace App\Component\EventSubscriber;
use App\Entity\Profil;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
use function Symfony\Component\String\s;
class AuthenticationSubscriber implements EventSubscriberInterface
{
private TokenStorageInterface $tokenStorage;
private RouterInterface $router;
private RequestStack $requestStack;
public function __construct(TokenStorageInterface $tokenStorage, RouterInterface $router, RequestStack $requestStack)
{
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
return [
AuthenticationSuccessEvent::class => 'onAuthenticationSuccess',
];
}
public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
{
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
if (!$user->getProfil() instanceof Profil) {
$request = $this->requestStack->getCurrentRequest();
$token = $event->getAuthenticationToken();
$this->tokenStorage->removeToken($token);
$request->getSession()->getFlashBag()->add('danger','Accès refusé');
$userAgent = $request->headers->get('User-Agent');
// réponse en mode JSON si l'user agent contient "postman" ou bien "okhttp"
if (!s(strtolower($userAgent))->containsAny(['postman', 'okhttp'])) {
$response = new RedirectResponse($this->router->generate('app_login'));
} else {
$response = new JsonResponse(['message' => 'Accès refusé']);
}
$response->send();
exit;
}
}
}