BxOAuthModule.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 OAuth2 OAuth2 server
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. require_once (BX_DIRECTORY_PATH_PLUGINS . 'OAuth2/Autoloader.php');
  12. OAuth2\Autoloader::register();
  13. class BxOAuthUserCredentialsStorage extends OAuth2\Storage\Pdo implements OAuth2\Storage\UserCredentialsInterface
  14. {
  15. public function checkUserCredentials($sLogin, $sPassword)
  16. {
  17. return ($sErrorMsg = bx_check_password($sLogin, $sPassword)) ? false : true;
  18. }
  19. public function getUser($sLogin)
  20. {
  21. return $this->getUserDetails($sLogin);
  22. }
  23. public function getUserDetails($sLogin)
  24. {
  25. if (!($oAccount = BxDolAccount::getInstance($sLogin)))
  26. return false;
  27. if (!($oProfile = BxDolProfile::getInstanceByAccount($oAccount->id())))
  28. return false;
  29. return array('user_id' => $oProfile->id());
  30. }
  31. public function checkRestrictedGrantType($iClientId, $sGrantType)
  32. {
  33. $aDetails = $this->getClientDetails($iClientId);
  34. if (isset($aDetails['grant_types'])) {
  35. $aGrantTypes = explode(',', $aDetails['grant_types']);
  36. return in_array($sGrantType, (array) $aGrantTypes);
  37. }
  38. // if grant_types are not defined, then none are restricted
  39. return true;
  40. }
  41. }
  42. class BxOAuthModule extends BxDolModule
  43. {
  44. protected $_oStorage;
  45. protected $_oServer;
  46. protected $_oAPI;
  47. function __construct(&$aModule)
  48. {
  49. parent::__construct($aModule);
  50. }
  51. public function initOAuth($sClientId)
  52. {
  53. if ($this->_oStorage)
  54. return;
  55. $aClient = array();
  56. // check cross origin request
  57. if (isset($_SERVER['HTTP_ORIGIN']) && parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST) != parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST)) {
  58. $aClient = $this->_oDb->getClientByAllowedOriginUrl($_SERVER['HTTP_ORIGIN']);
  59. if (!$aClient) {
  60. header('HTTP/1.0 403 Forbidden');
  61. echo _t("_Access denied");
  62. exit;
  63. }
  64. header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
  65. if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
  66. header('Access-Control-Allow-Methods: POST, GET');
  67. header('Access-Control-Allow-Headers: Authorization, Content-Type, X-Custom-Header, X-Requested-With');
  68. exit(0);
  69. }
  70. }
  71. // get the client data if it wasn't set before
  72. if (empty($aClient))
  73. $aClient = $sClientId ? $this->_oDb->getClientsBy(array('type' => 'client_id', 'client_id' => $sClientId)) : false;
  74. if (!$aClient)
  75. $aClient = array('grant_types' => 'authorization_code');
  76. if (!$aClient['grant_types'])
  77. $aClient['grant_types'] = 'authorization_code';
  78. $aGrantTypes = explode(',', $aClient['grant_types']);
  79. // configure OAuth storage and server
  80. $aConfig = array (
  81. 'client_table' => 'bx_oauth_clients',
  82. 'access_token_table' => 'bx_oauth_access_tokens',
  83. 'refresh_token_table' => 'bx_oauth_refresh_tokens',
  84. 'code_table' => 'bx_oauth_authorization_codes',
  85. 'user_table' => 'sys_accounts',
  86. 'jwt_table' => '',
  87. 'jti_table' => '',
  88. 'scope_table' => 'bx_oauth_scopes',
  89. 'public_key_table' => '',
  90. );
  91. if (in_array('refresh_token', $aGrantTypes)) {
  92. $aConfig['refresh_token'] = '';
  93. $aConfig['always_issue_new_refresh_token'] = true;
  94. $aConfig['unset_refresh_token_after_use'] = false;
  95. }
  96. $this->_oStorage = new BxOAuthUserCredentialsStorage(BxDolDb::getLink(), $aConfig);
  97. $this->_oServer = new OAuth2\Server($this->_oStorage, array(
  98. 'require_exact_redirect_uri' => false,
  99. 'refresh_token_lifetime' => 7776000, // set lifetime to 90 days
  100. ));
  101. // add grand types
  102. // Add the "Client Credentials" grant type (it is the simplest of the grant types)
  103. if (in_array('client_credentials', $aGrantTypes))
  104. $this->_oServer->addGrantType(new OAuth2\GrantType\ClientCredentials($this->_oStorage));
  105. // Add the "Authorization Code" grant type (this is where the oauth magic happens)
  106. if (in_array('authorization_code', $aGrantTypes))
  107. $this->_oServer->addGrantType(new OAuth2\GrantType\AuthorizationCode($this->_oStorage));
  108. // Add the "Password" grant type (generate client_id with empty client_secret)
  109. if (in_array('password', $aGrantTypes))
  110. $this->_oServer->addGrantType(new OAuth2\GrantType\UserCredentials($this->_oStorage));
  111. // Add the "Refresh Token" grant type
  112. if (in_array('refresh_token', $aGrantTypes))
  113. $this->_oServer->addGrantType(new OAuth2\GrantType\RefreshToken($this->_oStorage));
  114. }
  115. /**
  116. * @page public_api API Public
  117. * @section public_api_token /m/oauth2/token
  118. *
  119. * Get the token for the future communication with @ref private_api
  120. *
  121. * **HTTP Method:**
  122. * `POST`
  123. *
  124. * **Request params:**
  125. * - `grant_type` - for API it's better to use 'password' grant type
  126. * - `username` - login email
  127. * - `password` - login password
  128. * - `client_id` - client ID from bx_oauth_clients table
  129. *
  130. * **Response (success):**
  131. * @code
  132. * {
  133. * "access_token":"cdd7056d0adafa9ead87526ca22367c6b0df8273",
  134. * "expires_in":3600,
  135. * "token_type":"Bearer",
  136. * "scope":"basic",
  137. * "refresh_token":"c3d7f6f4b7cc640214ae0cba2b194872c3089f1c"
  138. * }
  139. * @endcode
  140. *
  141. * **Response (error):**
  142. * @code
  143. * {
  144. * "error":"short error description here",
  145. * "error_description":"long error description here"
  146. * }
  147. * @endcode
  148. */
  149. function actionToken ()
  150. {
  151. $this->initOAuth(bx_get('client_id'));
  152. // Handle a request for an OAuth2.0 Access Token and send the response to the client
  153. $this->_oServer->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
  154. }
  155. function actionApi ($sAction)
  156. {
  157. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  158. // Handle a request to a resource and authenticate the access token
  159. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  160. $this->_oServer->getResponse()->send();
  161. return;
  162. }
  163. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  164. if (!$this->_oAPI) {
  165. bx_import('API', $this->_aModule);
  166. $this->_oAPI = new BxOAuthAPI($this);
  167. }
  168. if (!$sAction || !method_exists($this->_oAPI, $sAction) || 0 === strcasecmp('errorOutput', $sAction) || 0 === strcasecmp('output', $sAction)) {
  169. $this->_oAPI->errorOutput(404, 'not_found', 'No such API endpoint available');
  170. return;
  171. }
  172. $aScope = explode(',', $this->_oAPI->aAction2Scope[$sAction]);
  173. $aScopeToken = explode(',', $aToken['scope']);
  174. if (!array_intersect($aScopeToken, $aScope)) {
  175. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  176. return;
  177. }
  178. $this->_oAPI->$sAction($aToken);
  179. }
  180. function actionAuth ()
  181. {
  182. $this->initOAuth(bx_get('client_id'));
  183. $oRequest = OAuth2\Request::createFromGlobals();
  184. $oResponse = new OAuth2\Response();
  185. // validate the authorize request
  186. if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
  187. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  188. $o = json_decode($oResponse->getResponseBody());
  189. $this->_oTemplate->getPage(false, MsgBox($o->error_description));
  190. }
  191. if (!isLogged()) {
  192. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  193. $sForceRelocate = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth/?client_id=' . bx_get('client_id') . '&response_type=' . bx_get('response_type') . '&scope=' . bx_get('scope') . '&state=' . bx_get('state') . '&redirect_uri=' . bx_get('redirect_uri');
  194. bx_login_form(false, false, $sForceRelocate);
  195. return;
  196. }
  197. $aProfiles = BxDolAccount::getInstance()->getProfiles();
  198. if (1 == count($aProfiles)) { // in case of one profile, don't display dialog with profiles choice
  199. $aProfile = array_pop($aProfiles);
  200. $_POST['profile_id'] = $aProfile['id'];
  201. }
  202. if (!($iProfileId = $this->_oDb->getSavedProfile(bx_get('client_id'), $aProfiles)) && empty($_POST)) {
  203. $oPage = BxDolPage::getObjectInstanceByURI('oauth-authorization');
  204. $this->_oTemplate->getPage(false, $oPage->getCode());
  205. return;
  206. }
  207. if (!$iProfileId)
  208. $iProfileId = bx_get('profile_id');
  209. $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool)$iProfileId, $iProfileId);
  210. $oResponse->send();
  211. }
  212. function serviceAuthorization ()
  213. {
  214. $sTitle = $this->_oDb->getClientTitle(bx_get('client_id'));
  215. $this->_oTemplate->addCss('main.css');
  216. return $this->_oTemplate->parseHtmlByName('page_auth.html', array(
  217. 'text' => _t('_bx_oauth_authorize_app', htmlspecialchars_adv($sTitle)),
  218. 'url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth',
  219. 'client_id' => bx_get('client_id'),
  220. 'response_type' => bx_get('response_type'),
  221. 'redirect_uri' => bx_get('redirect_uri'),
  222. 'scope' => bx_get('scope'),
  223. 'state' => bx_get('state'),
  224. 'profiles' => BxDolService::call('system', 'account_profile_switcher', array(getLoggedId(), false, "javascript: $('#bx-auth-profile-id').val('{profile_id}'); $('#bx-auth-form form').submit(); void(0);", true, _t('_bx_oauth_connect'), 'unit_wo_links'), 'TemplServiceProfiles')['content'],
  225. ));
  226. }
  227. function serviceGetClientsBy ($aParams = array())
  228. {
  229. return $this->_oDb->getClientsBy($aParams);
  230. }
  231. function serviceAddClient ($aClient)
  232. {
  233. if (!isset($aClient['client_id'])) {
  234. bx_import('FormAdd', 'bx_oauth');
  235. for ($i = 0; $i < 99 ; ++$i) {
  236. $aClient['client_id'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_ID, false));
  237. if (!$this->_oDb->getClientTitle($aClient['client_id'])) // check for uniq
  238. break;
  239. }
  240. }
  241. if (!isset($aClient['client_secret'])) {
  242. bx_import('FormAdd', 'bx_oauth');
  243. $aClient['client_secret'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_SECRET, false));
  244. }
  245. if (!isset($aClient['scope']))
  246. $aClient['scope'] = 'market';
  247. if (!isset($aClient['user_id']))
  248. $aClient['user_id'] = bx_get_logged_profile_id();
  249. if (!isset($aClient['title']) && isset($aClient['redirect_uri']) && ($sHost = parse_url($aClient['redirect_uri'], PHP_URL_HOST)))
  250. $aClient['title'] = $sHost;
  251. return $this->_oDb->addClient($aClient);
  252. }
  253. function serviceUpdateClientsBy ($aParamsSet, $aParamsWhere)
  254. {
  255. return $this->_oDb->updateClientsBy($aParamsSet, $aParamsWhere);
  256. }
  257. function serviceDeleteClientsBy ($aParams)
  258. {
  259. return $this->_oDb->deleteClientsBy($aParams);
  260. }
  261. function studioSettings ()
  262. {
  263. if (!isAdmin()) {
  264. $this->_oTemplate->displayAccessDenied ();
  265. return;
  266. }
  267. $oGrid = BxDolGrid::getObjectInstance('bx_oauth', BxDolStudioTemplate::getInstance());
  268. if ($oGrid)
  269. return $oGrid->getCode();
  270. return '';
  271. }
  272. function getClientIdFromAccessTokenHeader()
  273. {
  274. if (isset($_SERVER['HTTP_AUTHORIZATION']))
  275. $sAuthHeader = $_SERVER['HTTP_AUTHORIZATION'];
  276. elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
  277. $sAuthHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
  278. if (empty($sAuthHeader))
  279. return false;
  280. if (false === stripos($sAuthHeader, 'Bearer'))
  281. return false;
  282. return $this->_oDb->getClientIdByAccessToken(trim(substr($sAuthHeader, 6)));
  283. }
  284. }
  285. /** @} */