src/Api/Authentication/Authenticator.php line 106

Open in your IDE?
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: samuelp
  5. * Date: 1/21/18
  6. * Time: 2:10 PM
  7. */
  8. namespace App\Api\Authentication;
  9. use App\Entity\User;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  12. use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\AuthorizationHeaderTokenExtractor;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  17. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  18. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  19. use Symfony\Component\Security\Core\User\UserInterface;
  20. use Symfony\Component\Security\Core\User\UserProviderInterface;
  21. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  22. class Authenticator extends AbstractGuardAuthenticator {
  23. /**
  24. * @var JWTEncoderInterface
  25. */
  26. private $JWTEncoder;
  27. /**
  28. * @var EntityManagerInterface
  29. */
  30. private $entityManager;
  31. public function __construct(JWTEncoderInterface $JWTEncoder, EntityManagerInterface $entityManager) {
  32. $this->JWTEncoder = $JWTEncoder;
  33. $this->entityManager = $entityManager;
  34. }
  35. /**
  36. * Get the authentication credentials from the request and return them
  37. * as any type (e.g. an associate array).
  38. *
  39. * Whatever value you return here will be passed to getUser() and checkCredentials()
  40. *
  41. * For example, for a form login, you might:
  42. *
  43. * return array(
  44. * 'username' => $request->request->get('_username'),
  45. * 'password' => $request->request->get('_password'),
  46. * );
  47. *
  48. * Or for an API token that's on a header, you might use:
  49. *
  50. * return array('api_key' => $request->headers->get('X-API-TOKEN'));
  51. *
  52. * @param Request $request
  53. *
  54. * @return mixed Any non-null value
  55. *
  56. * @throws \UnexpectedValueException If null is returned
  57. */
  58. public function getCredentials(Request $request) {
  59. // dump($request);die;
  60. $extractor = new AuthorizationHeaderTokenExtractor(
  61. 'Bearer', 'Auth'
  62. );
  63. $token = $extractor->extract($request);
  64. if(!$token){
  65. return ;
  66. }
  67. return $token;
  68. }
  69. /**
  70. * Return a UserInterface object based on the credentials.
  71. *
  72. * The *credentials* are the return value from getCredentials()
  73. *
  74. * You may throw an AuthenticationException if you wish. If you return
  75. * null, then a UsernameNotFoundException is thrown for you.
  76. *
  77. * @param mixed $credentials
  78. * @param UserProviderInterface $userProvider
  79. *
  80. * @throws AuthenticationException
  81. *
  82. * @return UserInterface|null
  83. */
  84. public function getUser($credentials, UserProviderInterface $userProvider) {
  85. $data = null;
  86. try {
  87. $data = $this->JWTEncoder->decode($credentials);
  88. } catch (\Exception $e) {
  89. throw new \Symfony\Component\Security\Core\Exception\BadCredentialsException($e->getMessage(), 0, $e);
  90. }
  91. if($data === false){
  92. /*$response = [
  93. 'message' => "Invalid Token"
  94. ];*/
  95. throw new CustomUserMessageAuthenticationException("Invalid Token");
  96. }
  97. $id = $data['user_id'];
  98. return $this->entityManager->getRepository(User::class)->findOneBy([
  99. 'id' => $id
  100. ]);
  101. }
  102. /**
  103. * Returns true if the credentials are valid.
  104. *
  105. * If any value other than true is returned, authentication will
  106. * fail. You may also throw an AuthenticationException if you wish
  107. * to cause authentication to fail.
  108. *
  109. * The *credentials* are the return value from getCredentials()
  110. *
  111. * @param mixed $credentials
  112. * @param UserInterface $user
  113. *
  114. * @return bool
  115. *
  116. * @throws AuthenticationException
  117. */
  118. public function checkCredentials($credentials, UserInterface $user) {
  119. // TODO: Implement checkCredentials() method.
  120. return true;
  121. }
  122. /**
  123. * Called when authentication executed, but failed (e.g. wrong username password).
  124. *
  125. * This should return the Response sent back to the user, like a
  126. * RedirectResponse to the login page or a 403 response.
  127. *
  128. * If you return null, the request will continue, but the user will
  129. * not be authenticated. This is probably not what you want to do.
  130. *
  131. * @param Request $request
  132. * @param AuthenticationException $exception
  133. *
  134. * @return Response|null
  135. */
  136. public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
  137. // TODO: Implement onAuthenticationFailure() method.
  138. /* $response = new JsonResponse([
  139. 'error' => [
  140. 'message' => $exception->getMessage()
  141. ]
  142. ],Response::HTTP_UNAUTHORIZED );*/
  143. $response = new JsonResponse([
  144. 'error' => $exception->getMessage().': Please login again'
  145. ],Response::HTTP_UNAUTHORIZED );
  146. return $response;
  147. }
  148. /**
  149. * Called when authentication executed and was successful!
  150. *
  151. * This should return the Response sent back to the user, like a
  152. * RedirectResponse to the last page they visited.
  153. *
  154. * If you return null, the current request will continue, and the user
  155. * will be authenticated. This makes sense, for example, with an API.
  156. *
  157. * @param Request $request
  158. * @param TokenInterface $token
  159. * @param string $providerKey The provider (i.e. firewall) key
  160. *
  161. * @return Response|null
  162. */
  163. public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) {
  164. // TODO: Implement onAuthenticationSuccess() method.
  165. return;
  166. }
  167. /**
  168. * Does this method support remember me cookies?
  169. *
  170. * Remember me cookie will be set if *all* of the following are met:
  171. * A) This method returns true
  172. * B) The remember_me key under your firewall is configured
  173. * C) The "remember me" functionality is activated. This is usually
  174. * done by having a _remember_me checkbox in your form, but
  175. * can be configured by the "always_remember_me" and "remember_me_parameter"
  176. * parameters under the "remember_me" firewall key
  177. * D) The onAuthenticationSuccess method returns a Response object
  178. *
  179. * @return bool
  180. */
  181. public function supportsRememberMe() {
  182. // TODO: Implement supportsRememberMe() method.
  183. return false;
  184. }
  185. /**
  186. * Returns a response that directs the user to authenticate.
  187. *
  188. * This is called when an anonymous request accesses a resource that
  189. * requires authentication. The job of this method is to return some
  190. * response that "helps" the user start into the authentication process.
  191. *
  192. * Examples:
  193. * A) For a form login, you might redirect to the login page
  194. * return new RedirectResponse('/login');
  195. * B) For an API token authentication system, you return a 401 response
  196. * return new Response('Auth header required', 401);
  197. *
  198. * @param Request $request The request that resulted in an AuthenticationException
  199. * @param AuthenticationException $authException The exception that started the authentication process
  200. *
  201. * @return Response
  202. */
  203. public function start(Request $request, AuthenticationException $authException = null) {
  204. return new JsonResponse([
  205. 'error' => [
  206. 'message' => 'auth required'
  207. ]
  208. ], Response::HTTP_UNAUTHORIZED);
  209. }
  210. public function supports(Request $request): bool
  211. {
  212. // TODO: Implement supports() method.
  213. if($request->headers->get('Auth')){
  214. return true;
  215. }
  216. return false;
  217. }
  218. }