BxOAuthModule.php 16 KB

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