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 $JWTEncoderEntityManagerInterface $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($credentialsUserProviderInterface $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($credentialsUserInterface $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 $requestAuthenticationException $exception) {
  137.         // TODO: Implement onAuthenticationFailure() method.
  138.        /* $response = new JsonResponse([
  139.                 'error' => [
  140.                 'message' => $exception->getMessage()
  141.             ]
  142.         ],Response::HTTP_UNAUTHORIZED );*/
  143.         
  144.         $response = new JsonResponse([
  145.                 'error' => $exception->getMessage().': Please login again'
  146.         ],Response::HTTP_UNAUTHORIZED );
  147.         return $response;
  148.     }
  149.     /**
  150.      * Called when authentication executed and was successful!
  151.      *
  152.      * This should return the Response sent back to the user, like a
  153.      * RedirectResponse to the last page they visited.
  154.      *
  155.      * If you return null, the current request will continue, and the user
  156.      * will be authenticated. This makes sense, for example, with an API.
  157.      *
  158.      * @param Request $request
  159.      * @param TokenInterface $token
  160.      * @param string $providerKey The provider (i.e. firewall) key
  161.      *
  162.      * @return Response|null
  163.      */
  164.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey) {
  165.         // TODO: Implement onAuthenticationSuccess() method.
  166.         return;
  167.     }
  168.     /**
  169.      * Does this method support remember me cookies?
  170.      *
  171.      * Remember me cookie will be set if *all* of the following are met:
  172.      *  A) This method returns true
  173.      *  B) The remember_me key under your firewall is configured
  174.      *  C) The "remember me" functionality is activated. This is usually
  175.      *      done by having a _remember_me checkbox in your form, but
  176.      *      can be configured by the "always_remember_me" and "remember_me_parameter"
  177.      *      parameters under the "remember_me" firewall key
  178.      *  D) The onAuthenticationSuccess method returns a Response object
  179.      *
  180.      * @return bool
  181.      */
  182.     public function supportsRememberMe() {
  183.         // TODO: Implement supportsRememberMe() method.
  184.         return false;
  185.     }
  186.     /**
  187.      * Returns a response that directs the user to authenticate.
  188.      *
  189.      * This is called when an anonymous request accesses a resource that
  190.      * requires authentication. The job of this method is to return some
  191.      * response that "helps" the user start into the authentication process.
  192.      *
  193.      * Examples:
  194.      *  A) For a form login, you might redirect to the login page
  195.      *      return new RedirectResponse('/login');
  196.      *  B) For an API token authentication system, you return a 401 response
  197.      *      return new Response('Auth header required', 401);
  198.      *
  199.      * @param Request $request The request that resulted in an AuthenticationException
  200.      * @param AuthenticationException $authException The exception that started the authentication process
  201.      *
  202.      * @return Response
  203.      */
  204.     public function start(Request $requestAuthenticationException $authException null) {
  205.         return new JsonResponse([
  206.             'error' => [
  207.                 'message' => 'auth required'
  208.             ]
  209.         ], Response::HTTP_UNAUTHORIZED);
  210.     }
  211.     public function supports(Request $request): bool
  212.     {
  213.         // TODO: Implement supports() method.
  214.         if($request->headers->get('Auth')){
  215.             return true;
  216.         }
  217.         return false;
  218.     }
  219. }