/src/app/code/core/Mage/Oauth/Helper/Data.php

https://bitbucket.org/mkrasuski/magento-ce · PHP · 310 lines · 144 code · 29 blank · 137 comment · 19 complexity · 9ad92655975ce86bb2df598306c7ea4b MD5 · raw file

  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@magento.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magento.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Oauth
  23. * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * OAuth Helper
  28. *
  29. * @category Mage
  30. * @package Mage_Oauth
  31. * @author Magento Core Team <core@magentocommerce.com>
  32. */
  33. class Mage_Oauth_Helper_Data extends Mage_Core_Helper_Abstract
  34. {
  35. /**#@+
  36. * Endpoint types with appropriate routes
  37. */
  38. const ENDPOINT_AUTHORIZE_CUSTOMER = 'oauth/authorize';
  39. const ENDPOINT_AUTHORIZE_ADMIN = 'adminhtml/oauth_authorize';
  40. const ENDPOINT_AUTHORIZE_CUSTOMER_SIMPLE = 'oauth/authorize/simple';
  41. const ENDPOINT_AUTHORIZE_ADMIN_SIMPLE = 'adminhtml/oauth_authorize/simple';
  42. const ENDPOINT_INITIATE = 'oauth/initiate';
  43. const ENDPOINT_TOKEN = 'oauth/token';
  44. /**#@-*/
  45. /**#@+
  46. * Cleanup xpath config settings
  47. */
  48. const XML_PATH_CLEANUP_PROBABILITY = 'oauth/cleanup/cleanup_probability';
  49. const XML_PATH_CLEANUP_EXPIRATION_PERIOD = 'oauth/cleanup/expiration_period';
  50. /**#@-*/
  51. /**#@+ Email template */
  52. const XML_PATH_EMAIL_TEMPLATE = 'oauth/email/template';
  53. const XML_PATH_EMAIL_IDENTITY = 'oauth/email/identity';
  54. /**#@-*/
  55. /**
  56. * Cleanup expiration period in minutes
  57. */
  58. const CLEANUP_EXPIRATION_PERIOD_DEFAULT = 120;
  59. /**
  60. * Query parameter as a sign that user rejects
  61. */
  62. const QUERY_PARAM_REJECTED = 'rejected';
  63. /**
  64. * Available endpoints list
  65. *
  66. * @var array
  67. */
  68. protected $_endpoints = array(
  69. self::ENDPOINT_AUTHORIZE_CUSTOMER,
  70. self::ENDPOINT_AUTHORIZE_ADMIN,
  71. self::ENDPOINT_AUTHORIZE_CUSTOMER_SIMPLE,
  72. self::ENDPOINT_AUTHORIZE_ADMIN_SIMPLE,
  73. self::ENDPOINT_INITIATE,
  74. self::ENDPOINT_TOKEN
  75. );
  76. /**
  77. * Generate random string for token or secret or verifier
  78. *
  79. * @param int $length String length
  80. * @return string
  81. */
  82. protected function _generateRandomString($length)
  83. {
  84. if (function_exists('openssl_random_pseudo_bytes')) {
  85. // use openssl lib if it is install. It provides a better randomness
  86. $bytes = openssl_random_pseudo_bytes(ceil($length/2), $strong);
  87. $hex = bin2hex($bytes); // hex() doubles the length of the string
  88. $randomString = substr($hex, 0, $length); // we truncate at most 1 char if length parameter is an odd number
  89. } else {
  90. // fallback to mt_rand() if openssl is not installed
  91. /** @var $helper Mage_Core_Helper_Data */
  92. $helper = Mage::helper('core');
  93. $randomString = $helper->getRandomString(
  94. $length, Mage_Core_Helper_Data::CHARS_DIGITS . Mage_Core_Helper_Data::CHARS_LOWERS
  95. );
  96. }
  97. return $randomString;
  98. }
  99. /**
  100. * Generate random string for token
  101. *
  102. * @return string
  103. */
  104. public function generateToken()
  105. {
  106. return $this->_generateRandomString(Mage_Oauth_Model_Token::LENGTH_TOKEN);
  107. }
  108. /**
  109. * Generate random string for token secret
  110. *
  111. * @return string
  112. */
  113. public function generateTokenSecret()
  114. {
  115. return $this->_generateRandomString(Mage_Oauth_Model_Token::LENGTH_SECRET);
  116. }
  117. /**
  118. * Generate random string for verifier
  119. *
  120. * @return string
  121. */
  122. public function generateVerifier()
  123. {
  124. return $this->_generateRandomString(Mage_Oauth_Model_Token::LENGTH_VERIFIER);
  125. }
  126. /**
  127. * Generate random string for consumer key
  128. *
  129. * @return string
  130. */
  131. public function generateConsumerKey()
  132. {
  133. return $this->_generateRandomString(Mage_Oauth_Model_Consumer::KEY_LENGTH);
  134. }
  135. /**
  136. * Generate random string for consumer secret
  137. *
  138. * @return string
  139. */
  140. public function generateConsumerSecret()
  141. {
  142. return $this->_generateRandomString(Mage_Oauth_Model_Consumer::SECRET_LENGTH);
  143. }
  144. /**
  145. * Return complete callback URL or boolean FALSE if no callback provided
  146. *
  147. * @param Mage_Oauth_Model_Token $token Token object
  148. * @param bool $rejected OPTIONAL Add user reject sign
  149. * @return bool|string
  150. */
  151. public function getFullCallbackUrl(Mage_Oauth_Model_Token $token, $rejected = false)
  152. {
  153. $callbackUrl = $token->getCallbackUrl();
  154. if (Mage_Oauth_Model_Server::CALLBACK_ESTABLISHED == $callbackUrl) {
  155. return false;
  156. }
  157. if ($rejected) {
  158. /** @var $consumer Mage_Oauth_Model_Consumer */
  159. $consumer = Mage::getModel('oauth/consumer')->load($token->getConsumerId());
  160. if ($consumer->getId() && $consumer->getRejectedCallbackUrl()) {
  161. $callbackUrl = $consumer->getRejectedCallbackUrl();
  162. }
  163. } elseif (!$token->getAuthorized()) {
  164. Mage::throwException('Token is not authorized');
  165. }
  166. $callbackUrl .= (false === strpos($callbackUrl, '?') ? '?' : '&');
  167. $callbackUrl .= 'oauth_token=' . $token->getToken() . '&';
  168. $callbackUrl .= $rejected ? self::QUERY_PARAM_REJECTED . '=1' : 'oauth_verifier=' . $token->getVerifier();
  169. return $callbackUrl;
  170. }
  171. /**
  172. * Retrieve URL of specified endpoint.
  173. *
  174. * @param string $type Endpoint type (one of ENDPOINT_ constants)
  175. * @return string
  176. * @throws Exception Exception when endpoint not found
  177. */
  178. public function getProtocolEndpointUrl($type)
  179. {
  180. if (!in_array($type, $this->_endpoints)) {
  181. throw new Exception('Invalid endpoint type passed.');
  182. }
  183. return rtrim(Mage::getUrl($type), '/');
  184. }
  185. /**
  186. * Calculate cleanup possibility for data with lifetime property
  187. *
  188. * @return bool
  189. */
  190. public function isCleanupProbability()
  191. {
  192. // Safe get cleanup probability value from system configuration
  193. $configValue = (int) Mage::getStoreConfig(self::XML_PATH_CLEANUP_PROBABILITY);
  194. return $configValue > 0 ? 1 == mt_rand(1, $configValue) : false;
  195. }
  196. /**
  197. * Get cleanup expiration period value from system configuration in minutes
  198. *
  199. * @return int
  200. */
  201. public function getCleanupExpirationPeriod()
  202. {
  203. $minutes = (int) Mage::getStoreConfig(self::XML_PATH_CLEANUP_EXPIRATION_PERIOD);
  204. return $minutes > 0 ? $minutes : self::CLEANUP_EXPIRATION_PERIOD_DEFAULT;
  205. }
  206. /**
  207. * Send Email to Token owner
  208. *
  209. * @param string $userEmail
  210. * @param string $userName
  211. * @param string $applicationName
  212. * @param string $status
  213. */
  214. public function sendNotificationOnTokenStatusChange($userEmail, $userName, $applicationName, $status)
  215. {
  216. /* @var $mailTemplate Mage_Core_Model_Email_Template */
  217. $mailTemplate = Mage::getModel('core/email_template');
  218. $mailTemplate->sendTransactional(
  219. Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
  220. Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY),
  221. $userEmail,
  222. $userName,
  223. array(
  224. 'name' => $userName,
  225. 'email' => $userEmail,
  226. 'applicationName' => $applicationName,
  227. 'status' => $status,
  228. )
  229. );
  230. }
  231. /**
  232. * Is current authorize page is simple
  233. *
  234. * @return boolean
  235. */
  236. protected function _getIsSimple()
  237. {
  238. $simple = false;
  239. if (stristr($this->_getRequest()->getActionName(), 'simple')
  240. || !is_null($this->_getRequest()->getParam('simple', null))
  241. ) {
  242. $simple = true;
  243. }
  244. return $simple;
  245. }
  246. /**
  247. * Get authorize endpoint url
  248. *
  249. * @param string $userType
  250. * @return string
  251. */
  252. public function getAuthorizeUrl($userType)
  253. {
  254. $simple = $this->_getIsSimple();
  255. if (Mage_Oauth_Model_Token::USER_TYPE_CUSTOMER == $userType) {
  256. if ($simple) {
  257. $route = self::ENDPOINT_AUTHORIZE_CUSTOMER_SIMPLE;
  258. } else {
  259. $route = self::ENDPOINT_AUTHORIZE_CUSTOMER;
  260. }
  261. } elseif (Mage_Oauth_Model_Token::USER_TYPE_ADMIN == $userType) {
  262. if ($simple) {
  263. $route = self::ENDPOINT_AUTHORIZE_ADMIN_SIMPLE;
  264. } else {
  265. $route = self::ENDPOINT_AUTHORIZE_ADMIN;
  266. }
  267. } else {
  268. throw new Exception('Invalid user type.');
  269. }
  270. return $this->_getUrl($route, array('_query' => array('oauth_token' => $this->getOauthToken())));
  271. }
  272. /**
  273. * Retrieve oauth_token param from request
  274. *
  275. * @return string|null
  276. */
  277. public function getOauthToken()
  278. {
  279. return $this->_getRequest()->getParam('oauth_token', null);
  280. }
  281. }