src/webkul/uvdesk/api-bundle/Security/Guards/APIGuard.php line 41

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. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  19. use Doctrine\Persistence\ManagerRegistry;
  20. class APIGuard extends AbstractGuardAuthenticator
  21. {
  22. /**
  23. * [API-*] API Exception Codes
  24. */
  25. const API_UNAUTHORIZED = 'API-001';
  26. const API_NOT_AUTHENTICATED = 'API-002';
  27. const API_INSUFFICIENT_PARAMS = 'API-003';
  28. /**
  29. * [CC-*] Campus Connect Exception Codes
  30. */
  31. const USER_NOT_FOUND = 'CC-001';
  32. const INVALID_CREDNETIALS = 'CC-002';
  33. const UNEXPECTED_ERROR = 'CC-005';
  34. public function __construct(FirewallMap $firewall, ContainerInterface $container, EntityManagerInterface $entityManager, UserPasswordEncoderInterface $encoder)
  35. {
  36. $this->firewall = $firewall;
  37. $this->container = $container;
  38. $this->entityManager = $entityManager;
  39. $this->globalAuthEntityManager = $entityManager;
  40. $this->encoder = $encoder;
  41. }
  42. /**
  43. * Check whether this guard is applicable for the current request.
  44. */
  45. public function supports(Request $request)
  46. {
  47. return 'OPTIONS' != $request->getRealMethod() && 'uvdesk_api' === $this->firewall->getFirewallConfig($request)->getName();
  48. }
  49. /**
  50. * Retrieve and prepare credentials from the request.
  51. */
  52. public function getCredentials(Request $request)
  53. {
  54. // print_r("adadsa");
  55. // dd( $this->entityManager->getRepository(User::class,'global_auth')->findOneByEmail("snehal.yugasa@gmail.com"));
  56. $accessToken = null;
  57. $authorization = $request->headers->get('Authorization');
  58. // $parameters = json_decode($request->getContent(), true);
  59. //for admin
  60. // if($parameters['userType'] == 1){
  61. $authorization = "bearer.PSKTANSI8XIIFLXO0IV4GAVXQM7VUYVPB2FFOJKIKS0YAWWX4ZZK9MQNI63OOKDT";
  62. // $authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdGFmZklkIjoxNTAsImlhdCI6MTY5NDQzNDg4OH0.21KO-3183ALXji8vxCP1cDUEK0Q-P6Reao5OvWNydfA";
  63. // $tokenParts = explode(".", $authorization);
  64. // $tokenHeader = base64_decode($tokenParts[0]);
  65. // $tokenPayload = base64_decode($tokenParts[1]);
  66. // $jwtHeader = json_decode($tokenHeader);
  67. // $jwtPayload = json_decode($tokenPayload);
  68. // print $jwtPayload->username;
  69. // print_r($jwtPayload);
  70. // exit;
  71. // exit;
  72. // }else{
  73. // $authorization = $request->headers->get('Authorization');
  74. // }
  75. // dd($authorization);
  76. if (!empty($authorization) && strpos(strtolower($authorization), 'basic') === 0) {
  77. $accessToken = substr($authorization, 6);
  78. } else if (!empty($authorization) && strpos(strtolower($authorization), 'bearer') === 0) {
  79. $accessToken = substr($authorization, 7);
  80. }
  81. if (!empty($accessToken)) {
  82. try {
  83. if (in_array($request->attributes->get('_route'), ['uvdesk_api_bundle_sessions_api_v1.0_login_session'])) {
  84. list($email, $password) = explode(':', base64_decode($accessToken));
  85. return [
  86. 'email' => $email,
  87. 'password' => $password,
  88. ];
  89. } else {
  90. $user = $this->entityManager->getRepository(ApiAccessCredential::class)->getUserEmailByAccessToken($accessToken);
  91. // $test = $user = $this->globalAuthEntityManager->getRepository(ApiAccessCredential::class)
  92. // ->findOneBy(['accessToken' => $accessToken]);
  93. return [
  94. 'email' => $user['email'],
  95. 'accessToken' => $accessToken,
  96. ];
  97. }
  98. } catch (\Exception $e) {
  99. throw new AuthenticationException("An unexpected error occurred while authenticating credentials: {$e->getMessage()}");
  100. }
  101. }
  102. return [];
  103. }
  104. /**
  105. * Retrieve the current user on behalf of which the request is being performed.
  106. */
  107. public function getUser($credentials, UserProviderInterface $provider)
  108. {
  109. return !empty($credentials['email']) ? $provider->loadUserByUsername($credentials['email']) : null;
  110. }
  111. /**
  112. * Process the provided credentials and check whether the current request is properly authenticated.
  113. */
  114. public function checkCredentials($credentials, UserInterface $user)
  115. {
  116. if (!empty($credentials['password'])) {
  117. return $this->encoder->isPasswordValid($user, $credentials['password']);
  118. }
  119. if (!empty($credentials['accessToken'])) {
  120. $accessCredentials = $this->entityManager->getRepository(ApiAccessCredential::class)->findOneBy([
  121. 'user' => $user,
  122. 'token' => $credentials['accessToken'],
  123. ]);
  124. if (!empty($accessCredentials) && true == $accessCredentials->getIsEnabled() && false == $accessCredentials->getIsExpired()) {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. /**
  131. * Disable support for the "remember me" functionality.
  132. */
  133. public function supportsRememberMe()
  134. {
  135. return false;
  136. }
  137. public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
  138. {
  139. return null;
  140. }
  141. public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  142. {
  143. // dd($exception->getMessageKey());
  144. switch ($exception->getMessageKey()) {
  145. case 'Username could not be found.':
  146. $data = [
  147. 'status' => false,
  148. 'message' => 'No such user found',
  149. 'error_code' => self::USER_NOT_FOUND,
  150. ];
  151. break;
  152. case 'Invalid Credentials.':
  153. $data = [
  154. 'status' => false,
  155. 'message' => 'Invalid credentials provided.',
  156. 'error_code' => self::INVALID_CREDNETIALS,
  157. ];
  158. break;
  159. default:
  160. $data = [
  161. 'status' => false,
  162. 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  163. 'error_code' => self::UNEXPECTED_ERROR,
  164. ];
  165. break;
  166. }
  167. return new JsonResponse($data, Response::HTTP_FORBIDDEN);
  168. }
  169. public function start(Request $request, AuthenticationException $authException = null)
  170. {
  171. $data = [
  172. 'status' => false,
  173. 'message' => 'Authentication Required',
  174. 'error_code' => self::API_NOT_AUTHENTICATED,
  175. ];
  176. return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
  177. }
  178. }