src/Security/ApiAuthenticator.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Painel\Api;
  4. use App\Repository\Painel\ClienteRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  11. use Symfony\Component\Security\Core\User\UserInterface;
  12. use Symfony\Component\Security\Core\User\UserProviderInterface;
  13. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  14. use Symfony\Component\Security\Core\Security;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. class ApiAuthenticator extends AbstractGuardAuthenticator
  17. {
  18.     private $em;
  19.     private $container;
  20.     private $security;
  21.     private $clienteRepository;
  22.     public function __construct(
  23.         EntityManagerInterface $em,
  24.         Security $security,
  25.         ContainerInterface $container,
  26.         ClienteRepository $clienteRepository
  27.     )
  28.     {
  29.         $this->em $em;
  30.         $this->security $security;
  31.         $this->container $container;
  32.         $this->clienteRepository $clienteRepository;
  33.     }
  34.     /**
  35.      * Called on every request to decide if this authenticator should be
  36.      * used for the request. Returning `false` will cause this authenticator
  37.      * to be skipped.
  38.      */
  39.     public function supports(Request $request): bool
  40.     {
  41.         if($request->getMethod() == 'OPTIONS') {
  42.             return true;
  43.         }
  44.         return $request->headers->has('X-AUTH-CREDENCIAL') && $request->headers->has('X-AUTH-TOKEN');
  45.     }
  46.     /**
  47.      * Called on every request. Return whatever credentials you want to
  48.      * be passed to getUser() as $credentials.
  49.      */
  50.     public function getCredentials(Request $request)
  51.     {
  52.         if($request->getMethod() == 'OPTIONS') {
  53.             return true;
  54.         }
  55.         return ['credencial' => $request->headers->get('X-AUTH-CREDENCIAL'), 'token' => $request->headers->get('X-AUTH-TOKEN')];
  56.     }
  57.     public function getUser($credentialsUserProviderInterface $userProvider): ?UserInterface
  58.     {
  59.         if($this->container->get('request_stack')->getCurrentRequest()->getMethod() == 'OPTIONS') {
  60.             return $this->em->getRepository(Api::class)->find(1);
  61.         }
  62.         if (null === $credentials) {
  63.             // The token header was empty, authentication fails with HTTP Status
  64.             // Code 401 "Unauthorized"
  65.             return null;
  66.         }
  67.         
  68.         $this->user $this->em->getRepository(Api::class)->findOneBy($credentials);
  69.         // The "username" in this case is the apiToken, see the key `property`
  70.         // of `your_db_provider` in `security.yaml`.
  71.         // If this returns a user, checkCredentials() is called next:
  72.         return $this->em->getRepository(Api::class)->findOneBy($credentials);
  73.     }
  74.     public function checkCredentials($credentialsUserInterface $user): bool
  75.     {
  76.         // Check credentials - e.g. make sure the password is valid.
  77.         // In case of an API token, no credential check is needed.
  78.         // Return `true` to cause authentication success
  79.         return true;
  80.     }
  81.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $providerKey): ?Response
  82.     {
  83.         if($request->getMethod() == 'OPTIONS') {
  84.             return null;
  85.         }
  86.         $idCliente $token->getUser()->getIdCliente();
  87.         $cliente $this->clienteRepository->find($idCliente);
  88.         $this->container->get('doctrine.dbal.cliente_connection')->forceSwitch($cliente->getDbname(), $cliente->getHost());
  89.         return null;
  90.     }
  91.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  92.     {
  93.         $data = [
  94.             // you may want to customize or obfuscate the message first
  95.             'message' => 'Falha na autenticação. Verifique as credenciais no 2iM.DW - Painel.'
  96.             // or to translate this message
  97.             // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
  98.         ];
  99.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  100.     }
  101.     /**
  102.      * Called when authentication is needed, but it's not sent
  103.      */
  104.     public function start(Request $requestAuthenticationException $authException null): Response
  105.     {
  106.         if($request->getMethod() == 'OPTIONS') {
  107.             return true;
  108.         }
  109.         $data = [
  110.             // you might translate this message
  111.             'message' => 'Autenticação Obrigatória.'
  112.         ];
  113.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  114.     }
  115.     public function supportsRememberMe(): bool
  116.     {
  117.         return false;
  118.     }
  119. }