src/Security/TokenAuthenticator.php line 61

Open in your IDE?
  1. <?php
  2. // src/Security/TokenAuthenticator.php
  3. namespace App\Security;
  4. use App\Entity\ApiToken;
  5. use App\Entity\User;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  12. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  13. use Symfony\Component\Security\Core\User\UserInterface;
  14. use Symfony\Component\Security\Core\User\UserProviderInterface;
  15. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  16. class TokenAuthenticator extends AbstractGuardAuthenticator
  17. {
  18.     private $em;
  19.     public function __construct(EntityManagerInterface $em)
  20.     {
  21.         $this->em $em;
  22.     }
  23.     /**
  24.      * Called on every request to decide if this authenticator should be
  25.      * used for the request. Returning false will cause this authenticator
  26.      * to be skipped.
  27.      */
  28.     public function supports(Request $request): bool
  29.     {
  30.         return $request->headers->has('X-AUTH-TOKEN');
  31.     }
  32.     /**
  33.      * Called on every request. Return whatever credentials you want to
  34.      * be passed to getUser() as $credentials.
  35.      */
  36.     public function getCredentials(Request $request): mixed
  37.     {
  38.         return [
  39.             'token' => $request->headers->get('X-AUTH-TOKEN'),
  40.         ];
  41.     }
  42.     public function getUser($credentialsUserProviderInterface $userProvider): ?UserInterface
  43.     {
  44.         $apiToken $credentials['token'];
  45.         if (null === $apiToken) {
  46.             return null;
  47.         }
  48.         $apiToken $this->em->getRepository(ApiToken::class)
  49.             ->findOneBy(['token' => $apiToken]);
  50.         if(empty($apiToken) || $apiToken->getExpire() < new \DateTime()) {
  51.             throw new CustomUserMessageAuthenticationException('Authorization required - Token not found');
  52.         }
  53.         $apiToken->refreshToken();
  54.         $this->em->persist($apiToken);
  55.         $this->em->flush();
  56.         // if a User object, checkCredentials() is called
  57.         return $apiToken->getUser();
  58.     }
  59.     public function checkCredentials($credentialsUserInterface $user): bool
  60.     {
  61.         // check credentials - e.g. make sure the password is valid
  62.         // no credential check is needed in this case
  63.         // return true to cause authentication success
  64.         return true;
  65.     }
  66.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey): ?Response
  67.     {
  68.         // on success, let the request continue
  69.         return null;
  70.     }
  71.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  72.     {
  73.         $data = [
  74.             'message' => 'Authentication Required - ' strtr($exception->getMessageKey(), $exception->getMessageData())
  75.             // or to translate this message
  76.             // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
  77.         ];
  78.         return new JsonResponse($dataResponse::HTTP_FORBIDDEN);
  79.     }
  80.     /**
  81.      * Called when authentication is needed, but it's not sent
  82.      */
  83.     public function start(Request $requestAuthenticationException $authException null): Response
  84.     {
  85.         $data = [
  86.             // you might translate this message
  87.             'message' => 'Authentication Required'
  88.         ];
  89.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  90.     }
  91.     public function supportsRememberMe(): bool
  92.     {
  93.         return false;
  94.     }
  95. }