BxDolStudioOAuthOAuth2.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaStudio UNA Studio
  7. * @{
  8. */
  9. class BxDolStudioOAuthOAuth2 extends BxDolStudioOAuth implements iBxDolSingleton
  10. {
  11. protected $sSessionKeyStateToken;
  12. protected $sSessionKeyCsrfToken;
  13. protected $sSessionKeyCsrfTokenTime;
  14. protected $sApiUrl;
  15. protected $sScope;
  16. protected $sPageHandle;
  17. protected function __construct()
  18. {
  19. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  20. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  21. parent::__construct ();
  22. $this->sSessionKeyStateToken = 'bx_studio_store_state_token';
  23. $this->sSessionKeyCsrfToken = 'bx_studio_store_csrf_token';
  24. $this->sSessionKeyCsrfTokenTime = 'bx_studio_store_csrf_token_time';
  25. $this->sKey = $this->_getCredential('key');
  26. $this->sSecret = $this->_getCredential('secret');
  27. $this->sApiUrl = BX_DOL_MARKET_URL_ROOT . 'm/oauth2/';
  28. $this->sScope = 'market';
  29. $this->sPageHandle = BX_DOL_URL_STUDIO . 'store.php?page=goodies';
  30. $this->sDataRetrieveMethod = 'post';
  31. }
  32. public function __clone()
  33. {
  34. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  35. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  36. }
  37. public static function getInstance()
  38. {
  39. if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  40. $sClass = __CLASS__;
  41. $GLOBALS['bxDolClasses'][__CLASS__] = new $sClass();
  42. }
  43. return $GLOBALS['bxDolClasses'][__CLASS__];
  44. }
  45. protected function authorize()
  46. {
  47. if($this->isAuthorized())
  48. return true;
  49. $bCode = bx_get('code') !== false;
  50. $bState = bx_get('state') !== false;
  51. if($bCode && $bState && $this->_getState() != bx_get('state'))
  52. return _t('_adm_err_oauth_cannot_read_answer');
  53. //--- Get access token.
  54. if($bCode)
  55. return $this->getAccessToken(bx_get('code'));
  56. //--- Get request token and redirect to authorize.
  57. return $this->getRequestToken();
  58. }
  59. protected function getRequestToken()
  60. {
  61. $sUrl = bx_append_url_params($this->sApiUrl . 'auth', array(
  62. 'response_type' => 'code',
  63. 'client_id' => $this->sKey,
  64. 'redirect_uri' => $this->sPageHandle,
  65. 'scope' => $this->sScope,
  66. 'state' => $this->_genState(),
  67. ));
  68. return array(
  69. 'redirect' => $sUrl,
  70. 'message' => _t('_adm_msg_oauth_need_authorize', $sUrl)
  71. );
  72. }
  73. protected function getAccessToken($sCode)
  74. {
  75. $sResponse = bx_file_get_contents($this->sApiUrl . 'token', array(
  76. 'client_id' => $this->sKey,
  77. 'client_secret' => $this->sSecret,
  78. 'grant_type' => 'authorization_code',
  79. 'code' => $sCode,
  80. 'redirect_uri' => $this->sPageHandle,
  81. 'scope' => $this->sScope,
  82. ), $this->sDataRetrieveMethod);
  83. if (!$sResponse || ($aResponse = json_decode($sResponse, true)) === NULL || !isset($aResponse['access_token']) || isset($aResponse['error']))
  84. return isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  85. // get access_token
  86. $sAccessToken = $aResponse['access_token'];
  87. // request info about profile
  88. $sResponse = bx_file_get_contents($this->sApiUrl . 'api/me', array(), 'get', array(
  89. 'Authorization: Bearer ' . $sAccessToken,
  90. ));
  91. // handle error
  92. if (!$sResponse || ($aResponse = json_decode($sResponse, true)) === NULL || !$aResponse || isset($aResponse['error']))
  93. return isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  94. $this->oSession->setValue(self::$sSessionKeyToken, $sAccessToken);
  95. $this->oSession->setValue(self::$sSessionKeyAuthorized, 1);
  96. $this->oSession->setValue(self::$sSessionKeyAuthorizedUser, (int)$aResponse['id']);
  97. $this->oSession->setValue(self::$sSessionKeyAuthorizedOwner, (bool)$aResponse['owner'] ? 1 : 0);
  98. return true;
  99. }
  100. protected function fetch($aParams = array())
  101. {
  102. if(!$this->isAuthorized())
  103. return [];
  104. $iTimeout = 120;
  105. if(ini_get('safe_mode') == 0) {
  106. ini_set('max_execution_time', $iTimeout);
  107. ini_set('memory_limit', '512M');
  108. }
  109. $sHttpCode = null;
  110. $sResponse = bx_file_get_contents($this->sApiUrl . 'api/market', $aParams, 'post', [
  111. 'Authorization: Bearer ' . $this->oSession->getValue(self::$sSessionKeyToken),
  112. ], $sHttpCode, [], $iTimeout);
  113. //echo $sResponse; exit; //--- Uncomment to debug
  114. if (!$sResponse || ($aResponse = json_decode($sResponse, true)) === NULL || !$aResponse || isset($aResponse['error'])) {
  115. if(isset($aResponse['error']) && $this->isReloginRequired($aResponse['error']))
  116. $this->unsetAuthorizedUser();
  117. return isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  118. }
  119. return $aResponse['data'];
  120. }
  121. protected function isReloginRequired($sError)
  122. {
  123. if(in_array($sError, array('invalid_token', 'expired_token')))
  124. return true;
  125. return false;
  126. }
  127. protected function _getCredential($sName)
  128. {
  129. $sResult = getParam('sys_oauth_' . $sName);
  130. return $sResult !== false ? trim($sResult) : '';
  131. }
  132. protected function _genState()
  133. {
  134. $sResult = $this->_genCsrfToken();
  135. if($sResult !== false)
  136. return $sResult;
  137. return $this->_genStateToken();
  138. }
  139. protected function _getState()
  140. {
  141. $sResult = $this->_getCsrfToken();
  142. if($sResult !== false)
  143. return $sResult;
  144. return $this->_getStateToken();
  145. }
  146. protected function _genCsrfToken()
  147. {
  148. if(getParam('sys_security_form_token_enable') != 'on' || defined('BX_DOL_CRON_EXECUTE'))
  149. return false;
  150. $oSession = BxDolSession::getInstance();
  151. $iCsrfTokenLifetime = (int)getParam('sys_security_form_token_lifetime');
  152. $sToken = $oSession->getValue($this->sSessionKeyCsrfToken);
  153. if($sToken !== false && ($iCsrfTokenLifetime == 0 || time() - (int)$oSession->getValue($this->sSessionKeyCsrfTokenTime) < $iCsrfTokenLifetime))
  154. return $sToken;
  155. $sToken = genRndPwd(20, false);
  156. $oSession->setValue($this->sSessionKeyCsrfToken, $sToken);
  157. $oSession->setValue($this->sSessionKeyCsrfTokenTime, time());
  158. return $sToken;
  159. }
  160. protected function _getCsrfToken()
  161. {
  162. if(getParam('sys_security_form_token_enable') != 'on' || defined('BX_DOL_CRON_EXECUTE'))
  163. return false;
  164. return BxDolSession::getInstance()->getValue($this->sSessionKeyCsrfToken);
  165. }
  166. protected function _genStateToken()
  167. {
  168. $oSession = BxDolSession::getInstance();
  169. $sToken = $oSession->getValue($this->sSessionKeyStateToken);
  170. if($sToken !== false)
  171. return $sToken;
  172. $sToken = genRndPwd(20, false);
  173. $oSession->setValue($this->sSessionKeyStateToken, $sToken);
  174. return $sToken;
  175. }
  176. protected function _getStateToken()
  177. {
  178. return BxDolSession::getInstance()->getValue($this->sSessionKeyStateToken);
  179. }
  180. }
  181. /** @} */