OAuthProxyListener.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. namespace AuthBundle\Security\Firewall;
  3. use AuthBundle\Services\AccessTokenService;
  4. use Base\OAuthClientBundle\Security\Core\User\CustomOAuthUser;
  5. use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  8. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  11. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  12. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  13. use Symfony\Component\Security\Http\Firewall\ListenerInterface;
  14. use Symfony\Component\HttpFoundation\Request;
  15. class OAuthProxyListener implements ListenerInterface
  16. {
  17. /**
  18. * @var TokenStorageInterface
  19. */
  20. protected $tokenStorage;
  21. /**
  22. * @var AuthenticationManagerInterface
  23. */
  24. protected $authenticationManager;
  25. /**
  26. * @var AccessTokenService
  27. */
  28. protected $accessTokenService;
  29. /**
  30. * @param TokenStorageInterface $tokenStorage
  31. * @param AuthenticationManagerInterface $authenticationManager
  32. * @param AccessTokenService $accessTokenService
  33. */
  34. public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, AccessTokenService $accessTokenService)
  35. {
  36. $this->tokenStorage = $tokenStorage;
  37. $this->authenticationManager = $authenticationManager;
  38. $this->accessTokenService = $accessTokenService;
  39. }
  40. /**
  41. * Se crea el User y Token mediante alguno de los métodos
  42. *
  43. * 1. Http Basic
  44. * 2. Authorization
  45. * 3. Client Ip
  46. * 4. Firewalls
  47. *
  48. * @param GetResponseEvent $event
  49. */
  50. public function handle(GetResponseEvent $event)
  51. {
  52. $request = $event->getRequest();
  53. // verifico si la ip esta bloqueada. Se utiliza la variable API_CIDR_DENY para almacenar las ip o rangos de ip
  54. if (\AuthBundle\Utils\IpUtils::checkIpDeny($request->getClientIp())) {
  55. $error = true;
  56. } else if (($this->tokenStorage != null &&
  57. $this->tokenStorage->getToken() != null &&
  58. $this->tokenStorage->getToken() instanceof OAuthToken)) {
  59. // como los firewalls comparten info a traves del context no tengo que hacer nada, ya esta logueado.
  60. $error = false;
  61. } else if ($request->headers->has("php-auth-user") && $request->headers->has("php-auth-pw")) {
  62. // el header contiene php-auth-user && php-auth-pw
  63. $error = !$this->PHPAuth($request);
  64. } elseif ($request->headers->has("authorization")) {
  65. // el header contiene authorization
  66. $error = !$this->PHPAuthorization($request);
  67. } elseif ($request->getClientIp()) {
  68. $error = !$this->clientIp($request);
  69. } else {
  70. $error = true;
  71. }
  72. if ($error) {
  73. $this->deny($event);
  74. }
  75. }
  76. /**
  77. * @param GetResponseEvent $event
  78. */
  79. private function deny(GetResponseEvent $event)
  80. {
  81. $this->tokenStorage->setToken(null);
  82. $response = new Response();
  83. $response->setStatusCode(Response::HTTP_FORBIDDEN);
  84. $event->setResponse($response);
  85. echo 'The OAuth authentication failed.' . PHP_EOL;
  86. return;
  87. }
  88. /**
  89. * @param Request $request
  90. * @return bool Retorna TRUE si pudo crear y setear el CustomOAuthUser
  91. */
  92. private function PHPAuth(Request $request)
  93. {
  94. $username = $request->headers->get("php-auth-user");
  95. $password = $request->headers->get("php-auth-pw");
  96. $token = $this->accessTokenService->getToken($username, $password);
  97. unset($token['user_info']);
  98. $accessToken = $token;
  99. $auth_info = $this->accessTokenService->getUserInfo($username, $password);
  100. return $this->createCustomOAuthUser($username, $accessToken, $auth_info);
  101. }
  102. /**
  103. * Crea el custom user.
  104. * @param string $username
  105. * @param array $accessToken
  106. * @param array $auth_info
  107. * @return bool Retorna TRUE si pudo crear el CustomOAuthUser
  108. */
  109. private function createCustomOAuthUser(string $username, array $accessToken, array $auth_info)
  110. {
  111. try {
  112. $user = new CustomOAuthUser($username);
  113. if (count($auth_info)) {
  114. $user->setRoles($auth_info['roles']);
  115. $user->setTenancies($auth_info['tenancies']);
  116. $user->setTenancyCurrent($auth_info['tenancyCurrent']);
  117. }
  118. $token = new OAuthToken($accessToken, $user->getRoles());
  119. $token->setUser($user);
  120. $authToken = $this->authenticationManager->authenticate($token);
  121. $this->tokenStorage->setToken($authToken);
  122. return true;
  123. } catch (\Exception $failed) {
  124. var_dump($failed->getMessage());
  125. return false;
  126. }
  127. }
  128. /**
  129. * @param Request $request
  130. * @return bool Retorna TRUE si pudo crear y setear el CustomOAuthUser
  131. */
  132. private function PHPAuthorization($request)
  133. {
  134. $authorization = $request->headers->get("authorization");
  135. $pieces = explode(' ', $authorization);
  136. $accessToken = array(
  137. 'access_token' => $pieces[1],
  138. );
  139. $auth_info = $this->accessTokenService->requestUserInfo($authorization);
  140. if (isset($auth_info['username'])) {
  141. $username = $auth_info['username'];
  142. return $this->createCustomOAuthUser($username, $accessToken, $auth_info);
  143. } else {
  144. return false;
  145. }
  146. }
  147. /**
  148. * @param Request $request
  149. * @return bool Retorna TRUE si pudo crear y setear el CustomOAuthUser
  150. */
  151. private function clientIp($request)
  152. {
  153. $username = $clientIp = $request->getClientIp();
  154. if (\AuthBundle\Utils\IpUtils::checkIp($clientIp) === false) {
  155. return false;
  156. }
  157. // @TODO: Generar access token para el caso de IP valida
  158. $accessToken = array(
  159. 'access_token' => '',
  160. );
  161. $auth_info['roles'] = array('ROLE_USER');
  162. // @TODO: Traer la tenencia Base de la app Base
  163. $tenancy = array(
  164. 'id' => 1,
  165. 'name' => 'Tenencia Base',
  166. );
  167. $auth_info['tenancies'] = $auth_info['tenancyCurrent'] = $tenancy;
  168. return $this->createCustomOAuthUser($username, $accessToken, $auth_info);
  169. }
  170. }