Token.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Integration\Model\Oauth;
  7. use Magento\Authorization\Model\UserContextInterface;
  8. use Magento\Framework\Oauth\Exception as OauthException;
  9. use Magento\Framework\Oauth\Helper\Oauth as OauthHelper;
  10. use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection as TokenCollection;
  11. /**
  12. * oAuth token model
  13. *
  14. * @method string getName() Consumer name (joined from consumer table)
  15. * @method int getConsumerId()
  16. * @method Token setConsumerId() setConsumerId(int $consumerId)
  17. * @method int getAdminId()
  18. * @method Token setAdminId() setAdminId(int $adminId)
  19. * @method int getCustomerId()
  20. * @method Token setCustomerId() setCustomerId(int $customerId)
  21. * @method int getUserType()
  22. * @method Token setUserType() setUserType(int $userType)
  23. * @method string getType()
  24. * @method Token setType() setType(string $type)
  25. * @method string getCallbackUrl()
  26. * @method Token setCallbackUrl() setCallbackUrl(string $callbackUrl)
  27. * @method string getCreatedAt()
  28. * @method Token setCreatedAt() setCreatedAt(string $createdAt)
  29. * @method string getToken()
  30. * @method Token setToken() setToken(string $token)
  31. * @method string getSecret()
  32. * @method Token setSecret() setSecret(string $tokenSecret)
  33. * @method int getRevoked()
  34. * @method Token setRevoked() setRevoked(int $revoked)
  35. * @method int getAuthorized()
  36. * @method Token setAuthorized() setAuthorized(int $authorized)
  37. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  38. * @api
  39. * @since 100.0.2
  40. */
  41. class Token extends \Magento\Framework\Model\AbstractModel
  42. {
  43. /**#@+
  44. * Token types
  45. */
  46. const TYPE_REQUEST = 'request';
  47. const TYPE_ACCESS = 'access';
  48. const TYPE_VERIFIER = 'verifier';
  49. /**#@- */
  50. /**#@- */
  51. protected $_oauthHelper;
  52. /**
  53. * @var \Magento\Integration\Helper\Oauth\Data
  54. */
  55. protected $_oauthData;
  56. /**
  57. * @var \Magento\Integration\Model\Oauth\ConsumerFactory
  58. */
  59. protected $_consumerFactory;
  60. /**
  61. * @var \Magento\Framework\Url\Validator
  62. */
  63. protected $_urlValidator;
  64. /**
  65. * @var Consumer\Validator\KeyLengthFactory
  66. */
  67. protected $_keyLengthFactory;
  68. /**
  69. * Initialize dependencies.
  70. *
  71. * @param \Magento\Framework\Model\Context $context
  72. * @param \Magento\Framework\Registry $registry
  73. * @param \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory $keyLengthFactory
  74. * @param \Magento\Framework\Url\Validator $urlValidator
  75. * @param \Magento\Integration\Model\Oauth\ConsumerFactory $consumerFactory
  76. * @param \Magento\Integration\Helper\Oauth\Data $oauthData
  77. * @param OauthHelper $oauthHelper
  78. * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
  79. * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
  80. * @param array $data
  81. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  82. */
  83. public function __construct(
  84. \Magento\Framework\Model\Context $context,
  85. \Magento\Framework\Registry $registry,
  86. \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLengthFactory $keyLengthFactory,
  87. \Magento\Framework\Url\Validator $urlValidator,
  88. \Magento\Integration\Model\Oauth\ConsumerFactory $consumerFactory,
  89. \Magento\Integration\Helper\Oauth\Data $oauthData,
  90. OauthHelper $oauthHelper,
  91. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  92. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  93. array $data = []
  94. ) {
  95. parent::__construct($context, $registry, $resource, $resourceCollection, $data);
  96. $this->_keyLengthFactory = $keyLengthFactory;
  97. $this->_urlValidator = $urlValidator;
  98. $this->_consumerFactory = $consumerFactory;
  99. $this->_oauthData = $oauthData;
  100. $this->_oauthHelper = $oauthHelper;
  101. }
  102. /**
  103. * Initialize resource model
  104. *
  105. * @return void
  106. */
  107. protected function _construct()
  108. {
  109. $this->_init(\Magento\Integration\Model\ResourceModel\Oauth\Token::class);
  110. }
  111. /**
  112. * The "After save" actions
  113. *
  114. * @return $this
  115. */
  116. public function afterSave()
  117. {
  118. parent::afterSave();
  119. // Cleanup old entries
  120. if ($this->_oauthData->isCleanupProbability()) {
  121. $this->_getResource()->deleteOldEntries($this->_oauthData->getCleanupExpirationPeriod());
  122. }
  123. return $this;
  124. }
  125. /**
  126. * Generate an oauth_verifier for a consumer, if the consumer doesn't already have one.
  127. *
  128. * @param int $consumerId - The id of the consumer associated with the verifier to be generated.
  129. * @return $this
  130. */
  131. public function createVerifierToken($consumerId)
  132. {
  133. $tokenData = $this->getResource()->selectTokenByType($consumerId, self::TYPE_VERIFIER);
  134. $this->setData($tokenData ? $tokenData : []);
  135. if (!$this->getId()) {
  136. $this->setData(
  137. [
  138. 'consumer_id' => $consumerId,
  139. 'type' => self::TYPE_VERIFIER,
  140. 'token' => $this->_oauthHelper->generateToken(),
  141. 'secret' => $this->_oauthHelper->generateTokenSecret(),
  142. 'verifier' => $this->_oauthHelper->generateVerifier(),
  143. 'callback_url' => OauthHelper::CALLBACK_ESTABLISHED,
  144. 'user_type' => UserContextInterface::USER_TYPE_INTEGRATION, //As of now only integrations use Oauth
  145. ]
  146. );
  147. $this->validate();
  148. $this->save();
  149. }
  150. return $this;
  151. }
  152. /**
  153. * Convert token to access type
  154. *
  155. * @return $this
  156. * @throws OauthException
  157. */
  158. public function convertToAccess()
  159. {
  160. if (self::TYPE_REQUEST != $this->getType()) {
  161. throw new OauthException(__('Cannot convert to access token due to token is not request type'));
  162. }
  163. return $this->saveAccessToken(UserContextInterface::USER_TYPE_INTEGRATION);
  164. }
  165. /**
  166. * Create access token for a admin
  167. *
  168. * @param int $userId
  169. * @return $this
  170. */
  171. public function createAdminToken($userId)
  172. {
  173. $this->setAdminId($userId);
  174. return $this->saveAccessToken(UserContextInterface::USER_TYPE_ADMIN);
  175. }
  176. /**
  177. * Create access token for a customer
  178. *
  179. * @param int $userId
  180. * @return $this
  181. */
  182. public function createCustomerToken($userId)
  183. {
  184. $this->setCustomerId($userId);
  185. return $this->saveAccessToken(UserContextInterface::USER_TYPE_CUSTOMER, $userId);
  186. }
  187. /**
  188. * Generate and save request token
  189. *
  190. * @param int $entityId Token identifier
  191. * @param string $callbackUrl Callback URL
  192. * @return $this
  193. */
  194. public function createRequestToken($entityId, $callbackUrl)
  195. {
  196. $callbackUrl = !empty($callbackUrl) ? $callbackUrl : OauthHelper::CALLBACK_ESTABLISHED;
  197. $this->setData(
  198. [
  199. 'entity_id' => $entityId,
  200. 'type' => self::TYPE_REQUEST,
  201. 'token' => $this->_oauthHelper->generateToken(),
  202. 'secret' => $this->_oauthHelper->generateTokenSecret(),
  203. 'callback_url' => $callbackUrl,
  204. ]
  205. );
  206. $this->validate();
  207. $this->save();
  208. return $this;
  209. }
  210. /**
  211. * Get string representation of token
  212. *
  213. * @return string
  214. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  215. */
  216. public function __toString()
  217. {
  218. return http_build_query(['oauth_token' => $this->getToken(), 'oauth_token_secret' => $this->getSecret()]);
  219. }
  220. /**
  221. * Validate data
  222. *
  223. * @return bool
  224. * @throws OauthException Throw exception on fail validation
  225. */
  226. public function validate()
  227. {
  228. if (OauthHelper::CALLBACK_ESTABLISHED != $this->getCallbackUrl() && !$this->_urlValidator->isValid(
  229. $this->getCallbackUrl()
  230. )
  231. ) {
  232. $messages = $this->_urlValidator->getMessages();
  233. throw new OauthException(__(array_shift($messages)));
  234. }
  235. /** @var $validatorLength \Magento\Integration\Model\Oauth\Consumer\Validator\KeyLength */
  236. $validatorLength = $this->_keyLengthFactory->create();
  237. $validatorLength->setLength(OauthHelper::LENGTH_TOKEN_SECRET);
  238. $validatorLength->setName('Token Secret Key');
  239. if (!$validatorLength->isValid($this->getSecret())) {
  240. $messages = $validatorLength->getMessages();
  241. throw new OauthException(__(array_shift($messages)));
  242. }
  243. $validatorLength->setLength(OauthHelper::LENGTH_TOKEN);
  244. $validatorLength->setName('Token Key');
  245. if (!$validatorLength->isValid($this->getToken())) {
  246. $messages = $validatorLength->getMessages();
  247. throw new OauthException(__(array_shift($messages)));
  248. }
  249. if (null !== ($verifier = $this->getVerifier())) {
  250. $validatorLength->setLength(OauthHelper::LENGTH_TOKEN_VERIFIER);
  251. $validatorLength->setName('Verifier Key');
  252. if (!$validatorLength->isValid($verifier)) {
  253. $messages = $validatorLength->getMessages();
  254. throw new OauthException(__(array_shift($messages)));
  255. }
  256. }
  257. return true;
  258. }
  259. /**
  260. * Return the token's verifier.
  261. *
  262. * @return string
  263. */
  264. public function getVerifier()
  265. {
  266. return $this->getData('verifier');
  267. }
  268. /**
  269. * Generate and save access token for a given user type
  270. *
  271. * @param int $userType
  272. * @return $this
  273. */
  274. protected function saveAccessToken($userType)
  275. {
  276. $this->setUserType($userType);
  277. $this->setType(self::TYPE_ACCESS);
  278. $this->setToken($this->_oauthHelper->generateToken());
  279. $this->setSecret($this->_oauthHelper->generateTokenSecret());
  280. return $this->save();
  281. }
  282. /**
  283. * Get token by consumer and user type
  284. *
  285. * @param int $consumerId
  286. * @param int $userType
  287. * @return $this
  288. */
  289. public function loadByConsumerIdAndUserType($consumerId, $userType)
  290. {
  291. $tokenData = $this->getResource()->selectTokenByConsumerIdAndUserType($consumerId, $userType);
  292. $this->setData($tokenData ? $tokenData : []);
  293. return $this;
  294. }
  295. /**
  296. * Get token by admin id
  297. *
  298. * @param int $adminId
  299. * @return $this
  300. */
  301. public function loadByAdminId($adminId)
  302. {
  303. $tokenData = $this->getResource()->selectTokenByAdminId($adminId);
  304. $this->setData($tokenData ? $tokenData : []);
  305. return $this;
  306. }
  307. /**
  308. * Get token by customer id
  309. *
  310. * @param int $customerId
  311. * @return $this
  312. */
  313. public function loadByCustomerId($customerId)
  314. {
  315. $tokenData = $this->getResource()->selectTokenByCustomerId($customerId);
  316. $this->setData($tokenData ? $tokenData : []);
  317. return $this;
  318. }
  319. /**
  320. * Load token data by token.
  321. *
  322. * @param string $token
  323. * @return $this
  324. */
  325. public function loadByToken($token)
  326. {
  327. return $this->load($token, 'token');
  328. }
  329. }