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

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