src/Security/TokenAuthenticator.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Service\JwtService;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  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\User\UserInterface;
  13. use Symfony\Component\Security\Core\User\UserProviderInterface;
  14. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  15. class TokenAuthenticator extends AbstractGuardAuthenticator
  16. {
  17. private $em;
  18. /**
  19. * @var JwtService
  20. */
  21. private $jwtService;
  22. private $logger;
  23. public function __construct(
  24. EntityManagerInterface $em,
  25. JwtService $jwtService,
  26. LoggerInterface $logger
  27. ) {
  28. $this->em = $em;
  29. $this->jwtService = $jwtService;
  30. $this->logger = $logger;
  31. }
  32. /**
  33. * Called on every request to decide if this authenticator should be
  34. * used for the request. Returning `false` will cause this authenticator
  35. * to be skipped.
  36. */
  37. public function supports(Request $request): bool
  38. {
  39. return true;//$request->headers->has('Authorization');
  40. }
  41. /**
  42. * Called on every request. Return whatever credentials you want to
  43. * be passed to getUser() as $credentials.
  44. */
  45. public function getCredentials(Request $request)
  46. {
  47. return isset($_COOKIE['jwt']) ? $_COOKIE['jwt'] : ($request->headers->get('Authorization') ?: false);
  48. }
  49. public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface
  50. {
  51. try {
  52. $credentials = str_replace('Bearer ', '', $credentials);
  53. return $userProvider->loadUserByUsername($this->jwtService->getUser($credentials));
  54. } catch (\Exception $exception) {
  55. throw new AuthenticationException($exception->getMessage());
  56. }
  57. }
  58. public function checkCredentials($credentials, UserInterface $user): bool
  59. {
  60. // Check credentials - e.g. make sure the password is valid.
  61. // In case of an API token, no credential check is needed.
  62. // Return `true` to cause authentication success
  63. return true;
  64. }
  65. public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
  66. {
  67. $request->attributes->set('studentId', $token->getUser()->getId());
  68. // on success, let the request continue
  69. return null;
  70. }
  71. public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  72. {
  73. $data = [
  74. 'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
  75. ];
  76. $res = new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
  77. setcookie('jwt', null, time() - 1, '/', '', false, true);
  78. setcookie('isLoggedIn', false, time() - 1, '/', '', false, false);
  79. setcookie('role', false, time() - 1, '/', '', false, false);
  80. //setcookie('isAdmin',false,time()-1,'/','',false,false);
  81. // setcookie('isSuperAdmin',false,time()-1,'/','',false,false);
  82. return $res;
  83. }
  84. /**
  85. * Called when authentication is needed, but it's not sent
  86. */
  87. public function start(Request $request, AuthenticationException $authException = null): Response
  88. {
  89. $data = [
  90. 'message' => 'Authentication Required'
  91. ];
  92. return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
  93. }
  94. public function supportsRememberMe(): bool
  95. {
  96. return false;
  97. }
  98. }