BxOAuthModule.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. // don't allow login under another profile
  30. if ($oProfile->getAccountId() != $oAccount->id()) {
  31. // force switch to own profile
  32. if ($oAccount->updateProfileContextAuto())
  33. $oProfile = BxDolProfile::getInstanceByAccount($oAccount->id(), true);
  34. }
  35. if (!$oProfile)
  36. return false;
  37. return array('user_id' => $oProfile->id());
  38. }
  39. public function checkRestrictedGrantType($iClientId, $sGrantType)
  40. {
  41. $aDetails = $this->getClientDetails($iClientId);
  42. if (isset($aDetails['grant_types'])) {
  43. $aGrantTypes = explode(',', $aDetails['grant_types']);
  44. return in_array($sGrantType, (array) $aGrantTypes);
  45. }
  46. // if grant_types are not defined, then none are restricted
  47. return true;
  48. }
  49. }
  50. class BxOAuthModule extends BxDolModule
  51. {
  52. protected $_oStorage;
  53. protected $_oServer;
  54. protected $_oAPI;
  55. function __construct(&$aModule)
  56. {
  57. parent::__construct($aModule);
  58. }
  59. public function checkAllowedOrigins()
  60. {
  61. $aClient = array();
  62. if (isset($_SERVER['HTTP_ORIGIN']) && parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST) != parse_url(BX_DOL_URL_ROOT, PHP_URL_HOST)) {
  63. $aClient = $this->_oDb->getClientByAllowedOriginUrl($_SERVER['HTTP_ORIGIN']);
  64. if (!$aClient) {
  65. header('HTTP/1.0 403 Forbidden');
  66. echo _t("_Access denied");
  67. exit;
  68. }
  69. header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
  70. if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
  71. header('Access-Control-Allow-Methods: POST, GET');
  72. header('Access-Control-Allow-Headers: Authorization, Content-Type, X-Custom-Header, X-Requested-With');
  73. exit(0);
  74. }
  75. }
  76. return $aClient;
  77. }
  78. public function initOAuth($sClientId)
  79. {
  80. if ($this->_oStorage)
  81. return;
  82. // check cross origin request
  83. $aClient = $this->checkAllowedOrigins();
  84. // get the client data if it wasn't set before
  85. if (empty($aClient))
  86. $aClient = $sClientId ? $this->_oDb->getClientsBy(array('type' => 'client_id', 'client_id' => $sClientId)) : false;
  87. if (!$aClient)
  88. $aClient = array('grant_types' => 'authorization_code');
  89. if (!$aClient['grant_types'])
  90. $aClient['grant_types'] = 'authorization_code';
  91. $aGrantTypes = explode(',', $aClient['grant_types']);
  92. // configure OAuth storage and server
  93. $aConfig = array (
  94. 'client_table' => 'bx_oauth_clients',
  95. 'access_token_table' => 'bx_oauth_access_tokens',
  96. 'refresh_token_table' => 'bx_oauth_refresh_tokens',
  97. 'code_table' => 'bx_oauth_authorization_codes',
  98. 'user_table' => 'sys_accounts',
  99. 'jwt_table' => '',
  100. 'jti_table' => '',
  101. 'scope_table' => 'bx_oauth_scopes',
  102. 'public_key_table' => '',
  103. );
  104. $this->_oStorage = new BxOAuthUserCredentialsStorage(BxDolDb::getLink(), $aConfig);
  105. $this->_oServer = new OAuth2\Server($this->_oStorage, array(
  106. 'require_exact_redirect_uri' => false,
  107. 'refresh_token_lifetime' => 7776000, // set lifetime to 90 days
  108. ));
  109. // add grand types
  110. // Add the "Client Credentials" grant type (it is the simplest of the grant types)
  111. if (in_array('client_credentials', $aGrantTypes))
  112. $this->_oServer->addGrantType(new OAuth2\GrantType\ClientCredentials($this->_oStorage));
  113. // Add the "Authorization Code" grant type (this is where the oauth magic happens)
  114. if (in_array('authorization_code', $aGrantTypes))
  115. $this->_oServer->addGrantType(new OAuth2\GrantType\AuthorizationCode($this->_oStorage));
  116. // Add the "Password" grant type (generate client_id with empty client_secret)
  117. if (in_array('password', $aGrantTypes))
  118. $this->_oServer->addGrantType(new OAuth2\GrantType\UserCredentials($this->_oStorage));
  119. // Add the "Refresh Token" grant type
  120. if (in_array('refresh_token', $aGrantTypes))
  121. $this->_oServer->addGrantType(new OAuth2\GrantType\RefreshToken($this->_oStorage, array(
  122. 'always_issue_new_refresh_token' => true,
  123. // 'unset_refresh_token_after_use' => false,
  124. )));
  125. }
  126. /**
  127. * @page public_api API Public
  128. * @section public_api_token /m/oauth2/token
  129. *
  130. * Get the token for the future communication with @ref private_api
  131. *
  132. * **HTTP Method:**
  133. * `POST`
  134. *
  135. * **Request params:**
  136. * - `grant_type` - for API it's better to use 'password' grant type
  137. * - `username` - login email
  138. * - `password` - login password
  139. * - `client_id` - client ID from bx_oauth_clients table
  140. *
  141. * **Response (success):**
  142. * @code
  143. * {
  144. * "access_token":"cdd7056d0adafa9ead87526ca22367c6b0df8273",
  145. * "expires_in":3600,
  146. * "token_type":"Bearer",
  147. * "scope":"basic",
  148. * "refresh_token":"c3d7f6f4b7cc640214ae0cba2b194872c3089f1c"
  149. * }
  150. * @endcode
  151. *
  152. * **Response (error):**
  153. * @code
  154. * {
  155. * "error":"short error description here",
  156. * "error_description":"long error description here"
  157. * }
  158. * @endcode
  159. */
  160. function actionToken ()
  161. {
  162. $this->initOAuth(bx_get('client_id'));
  163. // Handle a request for an OAuth2.0 Access Token and send the response to the client
  164. $this->_oServer->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
  165. }
  166. /**
  167. * @page public_api API Public
  168. * @section public_api_revoke /m/oauth2/revoke
  169. *
  170. * Revoke token
  171. *
  172. * **HTTP Method:**
  173. * `POST`
  174. *
  175. * **Request params:**
  176. * - `token` - token to revoke
  177. *
  178. * **Request header:**
  179. * @code
  180. * Authorization: Bearer 9802c4a34e1535d8c3b721604ee0e7fb04116c49
  181. * @endcode
  182. *
  183. * **Response (success):**
  184. * @code
  185. * {
  186. * "revoked":true,
  187. * }
  188. * @endcode
  189. *
  190. * **Response (error):**
  191. * @code
  192. * {
  193. * "error":"short error description here",
  194. * "error_description":"long error description here"
  195. * }
  196. * @endcode
  197. */
  198. function actionRevoke ()
  199. {
  200. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  201. $this->_oServer->handleRevokeRequest(OAuth2\Request::createFromGlobals())->send();
  202. }
  203. /**
  204. * Authenicated or public call to the "safe" and "public" service methods
  205. */
  206. function actionCom ($sMethod)
  207. {
  208. if (!$this->_oAPI) {
  209. bx_import('API', $this->_aModule);
  210. $this->_oAPI = new BxOAuthAPI($this);
  211. }
  212. $bPublic = $this->_oAPI->isPublicAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod, bx_get('class') ? bx_get('class') : false);
  213. if ($bPublic) {
  214. $this->checkAllowedOrigins();
  215. $this->_oAPI->com($sMethod, array(), $bPublic);
  216. }
  217. else {
  218. if (!$this->_oAPI->isSafeAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod, bx_get('class') ? bx_get('class') : false)) {
  219. $this->_oAPI->errorOutput(403, 'access_denied', 'Only "public" and "safe" services can be called, or method doesn\'t exist');
  220. return;
  221. }
  222. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  223. // Handle a request to a resource and authenticate the access token
  224. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  225. $this->_oServer->getResponse()->send();
  226. return;
  227. }
  228. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  229. $aScope = explode(',', $this->_oAPI->aAction2Scope['api']);
  230. $aScopeToken = explode(',', $aToken['scope']);
  231. if (!array_intersect($aScopeToken, $aScope)) {
  232. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  233. return;
  234. }
  235. $this->_oAPI->com($sMethod, $aToken, false);
  236. }
  237. }
  238. /**
  239. * Authenicated call to the API
  240. */
  241. function actionApi ($sAction)
  242. {
  243. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  244. // Handle a request to a resource and authenticate the access token
  245. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  246. $this->_oServer->getResponse()->send();
  247. return;
  248. }
  249. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  250. if (!$this->_oAPI) {
  251. bx_import('API', $this->_aModule);
  252. $this->_oAPI = new BxOAuthAPI($this);
  253. }
  254. if (!$sAction || !method_exists($this->_oAPI, $sAction) || in_array($sAction, $this->_oAPI->aExceptionsAPI)) {
  255. $this->_oAPI->errorOutput(404, 'not_found', 'No such API endpoint available');
  256. return;
  257. }
  258. $aScope = explode(',', $this->_oAPI->aAction2Scope[$sAction]);
  259. $aScopeToken = explode(',', $aToken['scope']);
  260. if (!array_intersect($aScopeToken, $aScope)) {
  261. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  262. return;
  263. }
  264. $this->_oAPI->$sAction($aToken);
  265. }
  266. function actionAuth ()
  267. {
  268. $this->initOAuth(bx_get('client_id'));
  269. $oRequest = OAuth2\Request::createFromGlobals();
  270. $oResponse = new OAuth2\Response();
  271. // validate the authorize request
  272. if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
  273. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  274. $o = json_decode($oResponse->getResponseBody());
  275. $this->_oTemplate->getPage(false, MsgBox($o->error_description));
  276. }
  277. if (!isLogged()) {
  278. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  279. $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');
  280. bx_login_form(false, false, $sForceRelocate);
  281. return;
  282. }
  283. $aProfiles = BxDolAccount::getInstance()->getProfiles();
  284. if (1 == count($aProfiles)) { // in case of one profile, don't display dialog with profiles choice
  285. $aProfile = array_pop($aProfiles);
  286. $_POST['profile_id'] = $aProfile['id'];
  287. }
  288. if (!($iProfileId = $this->_oDb->getSavedProfile(bx_get('client_id'), $aProfiles)) && empty($_POST)) {
  289. $oPage = BxDolPage::getObjectInstanceByURI('oauth-authorization');
  290. $this->_oTemplate->getPage(false, $oPage->getCode());
  291. return;
  292. }
  293. if (!$iProfileId)
  294. $iProfileId = bx_get('profile_id');
  295. $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool)$iProfileId, $iProfileId);
  296. $oResponse->send();
  297. }
  298. function serviceAuthorization ()
  299. {
  300. $sTitle = $this->_oDb->getClientTitle(bx_get('client_id'));
  301. $this->_oTemplate->addCss('main.css');
  302. return $this->_oTemplate->parseHtmlByName('page_auth.html', array(
  303. 'text' => _t('_bx_oauth_authorize_app', htmlspecialchars_adv($sTitle)),
  304. 'url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth',
  305. 'client_id' => bx_get('client_id'),
  306. 'response_type' => bx_get('response_type'),
  307. 'redirect_uri' => bx_get('redirect_uri'),
  308. 'scope' => bx_get('scope'),
  309. 'state' => bx_get('state'),
  310. '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'],
  311. ));
  312. }
  313. function serviceGetClientsBy ($aParams = array())
  314. {
  315. return $this->_oDb->getClientsBy($aParams);
  316. }
  317. function serviceAddClient ($aClient)
  318. {
  319. if (!isset($aClient['client_id'])) {
  320. bx_import('FormAdd', 'bx_oauth');
  321. for ($i = 0; $i < 99 ; ++$i) {
  322. $aClient['client_id'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_ID, false));
  323. if (!$this->_oDb->getClientTitle($aClient['client_id'])) // check for uniq
  324. break;
  325. }
  326. }
  327. if (!isset($aClient['client_secret'])) {
  328. bx_import('FormAdd', 'bx_oauth');
  329. $aClient['client_secret'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_SECRET, false));
  330. }
  331. if (!isset($aClient['scope']))
  332. $aClient['scope'] = 'market';
  333. if (!isset($aClient['user_id']))
  334. $aClient['user_id'] = bx_get_logged_profile_id();
  335. if (!isset($aClient['title']) && isset($aClient['redirect_uri']) && ($sHost = parse_url($aClient['redirect_uri'], PHP_URL_HOST)))
  336. $aClient['title'] = $sHost;
  337. return $this->_oDb->addClient($aClient);
  338. }
  339. function serviceUpdateClientsBy ($aParamsSet, $aParamsWhere)
  340. {
  341. return $this->_oDb->updateClientsBy($aParamsSet, $aParamsWhere);
  342. }
  343. function serviceDeleteClientsBy ($aParams)
  344. {
  345. return $this->_oDb->deleteClientsBy($aParams);
  346. }
  347. function studioSettings ()
  348. {
  349. if (!isAdmin()) {
  350. $this->_oTemplate->displayAccessDenied ();
  351. return;
  352. }
  353. $oGrid = BxDolGrid::getObjectInstance('bx_oauth', BxDolStudioTemplate::getInstance());
  354. if ($oGrid)
  355. return $oGrid->getCode();
  356. return '';
  357. }
  358. function getClientIdFromAccessTokenHeader()
  359. {
  360. if (isset($_SERVER['HTTP_AUTHORIZATION']))
  361. $sAuthHeader = $_SERVER['HTTP_AUTHORIZATION'];
  362. elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
  363. $sAuthHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
  364. if (empty($sAuthHeader))
  365. return false;
  366. if (false === stripos($sAuthHeader, 'Bearer'))
  367. return false;
  368. return $this->_oDb->getClientIdByAccessToken(trim(substr($sAuthHeader, 6)));
  369. }
  370. }
  371. /** @} */