vendor/uvdesk/api-bundle/Security/Guards/APIGuard.php line 39

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\ApiBundle\Security\Guards;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. use Symfony\Component\DependencyInjection\ContainerInterface;
  10. use Symfony\Component\Security\Core\User\UserProviderInterface;
  11. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  12. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  13. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use Webkul\UVDesk\ApiBundle\Entity\ApiAccessCredential;
  16. class APIGuard extends AbstractGuardAuthenticator
  17. {
  18.     /**
  19.      * [API-*] API Exception Codes
  20.      */
  21.     const API_UNAUTHORIZED 'API-001';
  22.     const API_NOT_AUTHENTICATED 'API-002';
  23.     const API_INSUFFICIENT_PARAMS 'API-003';
  24.     /**
  25.      * [CC-*] Campus Connect Exception Codes
  26.      */
  27.     const USER_NOT_FOUND 'CC-001';
  28.     const INVALID_CREDNETIALS 'CC-002';
  29.     const UNEXPECTED_ERROR 'CC-005';
  30.     public function __construct(FirewallMap $firewallContainerInterface $containerEntityManagerInterface $entityManagerUserPasswordEncoderInterface $encoder)
  31.     {
  32.         $this->firewall $firewall;
  33.         $this->container $container;
  34.         $this->entityManager $entityManager;
  35.         $this->encoder $encoder;
  36.     }
  37.     /**
  38.      * Check whether this guard is applicable for the current request.
  39.      */
  40.     public function supports(Request $request)
  41.     {
  42.         return 'OPTIONS' != $request->getRealMethod() && 'uvdesk_api' === $this->firewall->getFirewallConfig($request)->getName();
  43.     }
  44.     /**
  45.      * Retrieve and prepare credentials from the request.
  46.      */
  47.     public function getCredentials(Request $request)
  48.     {
  49.         $accessToken null;
  50.         $authorization $request->headers->get('Authorization');
  51.         if (!empty($authorization) && strpos(strtolower($authorization), 'basic') === 0) {
  52.             $accessToken substr($authorization6);
  53.         } else if (!empty($authorization) && strpos(strtolower($authorization), 'bearer') === 0) {
  54.             $accessToken substr($authorization7);
  55.         }
  56.         if (!empty($accessToken)) {
  57.             try {
  58.                 if (in_array($request->attributes->get('_route'), ['uvdesk_api_bundle_sessions_api_v1.0_login_session'])) {
  59.                     list($email$password) = explode(':'base64_decode($accessToken));
  60.                     return [
  61.                         'email'    => $email
  62.                         'password' => $password
  63.                     ];
  64.                 } else {
  65.                     $user $this->entityManager->getRepository(ApiAccessCredential::class)->getUserEmailByAccessToken($accessToken);
  66.                     
  67.                     return [
  68.                         'email'       => $user['email'], 
  69.                         'accessToken' => $accessToken
  70.                     ];
  71.                 }
  72.             } catch (\Exception $e) {
  73.                 throw new AuthenticationException("An unexpected error occurred while authenticating credentials: {$e->getMessage()}");
  74.             }
  75.         }
  76.         
  77.         return [];
  78.     }
  79.     /**
  80.      * Retrieve the current user on behalf of which the request is being performed.
  81.      */
  82.     public function getUser($credentialsUserProviderInterface $provider)
  83.     {
  84.         return !empty($credentials['email']) ? $provider->loadUserByUsername($credentials['email']) : null;
  85.     }
  86.     /**
  87.      * Process the provided credentials and check whether the current request is properly authenticated.
  88.      */
  89.     public function checkCredentials($credentialsUserInterface $user)
  90.     {
  91.         if (!empty($credentials['password'])) {
  92.             return $this->encoder->isPasswordValid($user$credentials['password']);
  93.         }
  94.         if (!empty($credentials['accessToken'])) {
  95.             $accessCredentials $this->entityManager->getRepository(ApiAccessCredential::class)->findOneBy([
  96.                 'user'  => $user,
  97.                 'token' => $credentials['accessToken'],
  98.             ]);
  99.             if (
  100.                 ! empty($accessCredentials)
  101.                 && true == $accessCredentials->getIsEnabled()
  102.                 && false == $accessCredentials->getIsExpired()
  103.             ) {
  104.                 return true;
  105.             }
  106.         }
  107.         return false;
  108.     }
  109.     /**
  110.      * Disable support for the "remember me" functionality.
  111.      */
  112.     public function supportsRememberMe()
  113.     {
  114.         return false;
  115.     }
  116.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  117.     {
  118.         return null;
  119.     }
  120.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception)
  121.     {
  122.         switch ($exception->getMessageKey()) {
  123.             case 'Username could not be found.':
  124.                 $data = [
  125.                     'status'     => false,
  126.                     'message'    => 'No such user found',
  127.                     'error_code' => self::USER_NOT_FOUND,
  128.                 ];
  129.                 
  130.                 break;
  131.             case 'Invalid Credentials.':
  132.                 $data = [
  133.                     'status'     => false,
  134.                     'message'    => 'Invalid credentials provided.',
  135.                     'error_code' => self::INVALID_CREDNETIALS,
  136.                 ];
  137.                 break;
  138.             case 'An authentication exception occurred.':
  139.                 if ($request->attributes->get('_route') == 'uvdesk_api_bundle_sessions_api_v1.0_logout_session'){
  140.                     $data = [
  141.                         'status'     => false,
  142.                         'message'    => 'This Session token has been already expired successfully.',
  143.                         'error_code' => self::INVALID_CREDNETIALS,
  144.                     ];
  145.                     return new JsonResponse($dataResponse::HTTP_FORBIDDEN);
  146.                 }
  147.                 $data = [
  148.                     'status'     => false,
  149.                     'message'    => 'This api is disabled from admin end, please check once again.',
  150.                     'error_code' => self::INVALID_CREDNETIALS,
  151.                 ];
  152.                 
  153.                 break;
  154.             default:
  155.                 $data = [
  156.                     'status'     => false,
  157.                     'message'    => strtr($exception->getMessageKey(), $exception->getMessageData()),
  158.                     'error_code' => self::UNEXPECTED_ERROR,
  159.                 ];
  160.                 break;
  161.         }
  162.         return new JsonResponse($dataResponse::HTTP_FORBIDDEN);
  163.     }
  164.     public function start(Request $requestAuthenticationException $authException null)
  165.     {
  166.         $data = [
  167.             'status'     => false,
  168.             'message'    => 'Authentication Required',
  169.             'error_code' => self::API_NOT_AUTHENTICATED,
  170.         ];
  171.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  172.     }
  173. }