OauthHelper.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /**
  3. * Helper class for generating OAuth related credentials
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\TestFramework\Authentication;
  9. use Magento\TestFramework\Authentication\Rest\OauthClient;
  10. use Magento\TestFramework\Helper\Bootstrap;
  11. use OAuth\Common\Consumer\Credentials;
  12. use Zend\Stdlib\Exception\LogicException;
  13. use Magento\Integration\Model\Integration;
  14. class OauthHelper
  15. {
  16. /** @var array */
  17. protected static $_apiCredentials;
  18. /**
  19. * Generate authentication credentials
  20. * @param string $date consumer creation date
  21. * @return array
  22. * <pre>
  23. * array (
  24. * 'key' => 'ajdsjashgdkahsdlkjasldkjals', //consumer key
  25. * 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //consumer secret
  26. * 'verifier' => 'oiudioqueoiquweoiqwueoqwuii'
  27. * 'consumer' => $consumer, // retrieved consumer Model
  28. * 'token' => $token // retrieved token Model
  29. * );
  30. * </pre>
  31. */
  32. public static function getConsumerCredentials($date = null)
  33. {
  34. $integration = self::_createIntegration('all');
  35. $objectManager = Bootstrap::getObjectManager();
  36. /** @var $oauthService \Magento\Integration\Api\OauthServiceInterface */
  37. $oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
  38. $consumer = $oauthService->loadConsumer($integration->getConsumerId());
  39. $url = TESTS_BASE_URL;
  40. $consumer->setCallbackUrl($url);
  41. $consumer->setRejectedCallbackUrl($url);
  42. if ($date !== null) {
  43. $consumer->setCreatedAt($date);
  44. }
  45. $consumer->save();
  46. $token = $objectManager->create(\Magento\Integration\Model\Oauth\Token::class);
  47. $verifier = $token->createVerifierToken($consumer->getId())->getVerifier();
  48. return [
  49. 'key' => $consumer->getKey(),
  50. 'secret' => $consumer->getSecret(),
  51. 'verifier' => $verifier,
  52. 'consumer' => $consumer,
  53. 'token' => $token
  54. ];
  55. }
  56. /**
  57. * Create an access token to associated to a consumer to access APIs. No resources are available to this consumer.
  58. *
  59. * @return array comprising of token key and secret
  60. * <pre>
  61. * array (
  62. * 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
  63. * 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
  64. * 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
  65. * );
  66. * </pre>
  67. */
  68. public static function getAccessToken()
  69. {
  70. $consumerCredentials = self::getConsumerCredentials();
  71. $credentials = new Credentials($consumerCredentials['key'], $consumerCredentials['secret'], TESTS_BASE_URL);
  72. $oAuthClient = new OauthClient($credentials);
  73. $requestToken = $oAuthClient->requestRequestToken();
  74. $accessToken = $oAuthClient->requestAccessToken(
  75. $requestToken->getRequestToken(),
  76. $consumerCredentials['verifier'],
  77. $requestToken->getRequestTokenSecret()
  78. );
  79. /** TODO: Reconsider return format. It is not aligned with method name. */
  80. return [
  81. 'key' => $accessToken->getAccessToken(),
  82. 'secret' => $accessToken->getAccessTokenSecret(),
  83. 'oauth_client' => $oAuthClient
  84. ];
  85. }
  86. /**
  87. * Create an access token, tied to integration which has permissions to all API resources in the system.
  88. *
  89. * @param array $resources list of resources to grant to the integration
  90. * @param \Magento\Integration\Model\Integration|null $integrationModel
  91. * @return array
  92. * <pre>
  93. * array (
  94. * 'key' => 'ajdsjashgdkahsdlkjasldkjals', //token key
  95. * 'secret' => 'alsjdlaskjdlaksjdlasjkdlas', //token secret
  96. * 'oauth_client' => $oauthClient // OauthClient instance used to fetch the access token
  97. * 'integration' => $integration // Integration instance associated with access token
  98. * );
  99. * </pre>
  100. * @throws LogicException
  101. */
  102. public static function getApiAccessCredentials($resources = null, Integration $integrationModel = null)
  103. {
  104. if (!self::$_apiCredentials) {
  105. $integration = $integrationModel === null ? self::_createIntegration($resources) : $integrationModel;
  106. $objectManager = Bootstrap::getObjectManager();
  107. /** @var \Magento\Integration\Api\OauthServiceInterface $oauthService */
  108. $oauthService = $objectManager->get(\Magento\Integration\Api\OauthServiceInterface::class);
  109. $oauthService->createAccessToken($integration->getConsumerId());
  110. $accessToken = $oauthService->getAccessToken($integration->getConsumerId());
  111. if (!$accessToken) {
  112. throw new LogicException('Access token was not created.');
  113. }
  114. $consumer = $oauthService->loadConsumer($integration->getConsumerId());
  115. $credentials = new Credentials($consumer->getKey(), $consumer->getSecret(), TESTS_BASE_URL);
  116. /** @var $oAuthClient OauthClient */
  117. $oAuthClient = new OauthClient($credentials);
  118. self::$_apiCredentials = [
  119. 'key' => $accessToken->getToken(),
  120. 'secret' => $accessToken->getSecret(),
  121. 'oauth_client' => $oAuthClient,
  122. 'integration' => $integration,
  123. ];
  124. }
  125. return self::$_apiCredentials;
  126. }
  127. /**
  128. * Forget API access credentials.
  129. */
  130. public static function clearApiAccessCredentials()
  131. {
  132. self::$_apiCredentials = false;
  133. }
  134. /**
  135. * Remove fs element with nested elements.
  136. *
  137. * @param string $dir
  138. * @param bool $doSaveRoot
  139. */
  140. protected static function _rmRecursive($dir, $doSaveRoot = false)
  141. {
  142. if (is_dir($dir)) {
  143. foreach (glob($dir . '/*') as $object) {
  144. if (is_dir($object)) {
  145. self::_rmRecursive($object);
  146. } else {
  147. unlink($object);
  148. }
  149. }
  150. if (!$doSaveRoot) {
  151. rmdir($dir);
  152. }
  153. } else {
  154. unlink($dir);
  155. }
  156. }
  157. /**
  158. * Create integration instance.
  159. *
  160. * @param array $resources
  161. * @return \Magento\Integration\Model\Integration
  162. * @throws \Zend\Stdlib\Exception\LogicException
  163. */
  164. protected static function _createIntegration($resources)
  165. {
  166. $objectManager = Bootstrap::getObjectManager();
  167. /** @var $integrationService \Magento\Integration\Api\IntegrationServiceInterface */
  168. $integrationService = $objectManager->get(\Magento\Integration\Api\IntegrationServiceInterface::class);
  169. $params = ['name' => 'Integration' . microtime()];
  170. if ($resources === null || $resources == 'all') {
  171. $params['all_resources'] = true;
  172. } else {
  173. $params['resource'] = $resources;
  174. }
  175. $integration = $integrationService->create($params);
  176. $integration->setStatus(\Magento\Integration\Model\Integration::STATUS_ACTIVE)->save();
  177. /** Magento cache must be cleared to activate just created ACL role. */
  178. $varPath = realpath(BP . '/var');
  179. if (!$varPath) {
  180. throw new LogicException("Magento cache cannot be cleared after new ACL role creation.");
  181. } else {
  182. $cachePath = $varPath . '/cache';
  183. if (is_dir($cachePath)) {
  184. self::_rmRecursive($cachePath, true);
  185. }
  186. }
  187. return $integration;
  188. }
  189. }