BxOAuthModule.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. $iRefreshTokenLifetime = (int)getParam('bx_oauth2_refresh_token_lifetime');
  106. $this->_oServer = new OAuth2\Server($this->_oStorage, array(
  107. 'require_exact_redirect_uri' => false,
  108. 'refresh_token_lifetime' => $iRefreshTokenLifetime ? $iRefreshTokenLifetime : 7779000, // set lifetime to 90 days
  109. ));
  110. // add grand types
  111. // Add the "Client Credentials" grant type (it is the simplest of the grant types)
  112. if (in_array('client_credentials', $aGrantTypes))
  113. $this->_oServer->addGrantType(new OAuth2\GrantType\ClientCredentials($this->_oStorage));
  114. // Add the "Authorization Code" grant type (this is where the oauth magic happens)
  115. if (in_array('authorization_code', $aGrantTypes))
  116. $this->_oServer->addGrantType(new OAuth2\GrantType\AuthorizationCode($this->_oStorage));
  117. // Add the "Password" grant type (generate client_id with empty client_secret)
  118. if (in_array('password', $aGrantTypes))
  119. $this->_oServer->addGrantType(new OAuth2\GrantType\UserCredentials($this->_oStorage));
  120. // Add the "Refresh Token" grant type
  121. if (in_array('refresh_token', $aGrantTypes))
  122. $this->_oServer->addGrantType(new OAuth2\GrantType\RefreshToken($this->_oStorage, array(
  123. 'always_issue_new_refresh_token' => getParam('bx_oauth2_always_issue_new_refresh_token') ? true : false,
  124. // 'unset_refresh_token_after_use' => false,
  125. )));
  126. }
  127. /**
  128. * @page public_api API Public
  129. * @section public_api_token /m/oauth2/token
  130. *
  131. * Get the token for the future communication with @ref private_api
  132. *
  133. * **HTTP Method:**
  134. * `POST`
  135. *
  136. * **Request params:**
  137. * - `grant_type` - for API it's better to use 'password' grant type
  138. * - `username` - login email
  139. * - `password` - login password
  140. * - `client_id` - client ID from bx_oauth_clients table
  141. *
  142. * **Response (success):**
  143. * @code
  144. * {
  145. * "access_token":"cdd7056d0adafa9ead87526ca22367c6b0df8273",
  146. * "expires_in":3600,
  147. * "token_type":"Bearer",
  148. * "scope":"basic",
  149. * "refresh_token":"c3d7f6f4b7cc640214ae0cba2b194872c3089f1c"
  150. * }
  151. * @endcode
  152. *
  153. * **Response (error):**
  154. * @code
  155. * {
  156. * "error":"short error description here",
  157. * "error_description":"long error description here"
  158. * }
  159. * @endcode
  160. */
  161. function actionToken ()
  162. {
  163. $this->initOAuth(bx_get('client_id'));
  164. // Handle a request for an OAuth2.0 Access Token and send the response to the client
  165. $this->_oServer->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
  166. }
  167. /**
  168. * @page public_api API Public
  169. * @section public_api_revoke /m/oauth2/revoke
  170. *
  171. * Revoke token
  172. *
  173. * **HTTP Method:**
  174. * `POST`
  175. *
  176. * **Request params:**
  177. * - `token` - token to revoke
  178. *
  179. * **Request header:**
  180. * @code
  181. * Authorization: Bearer 9802c4a34e1535d8c3b721604ee0e7fb04116c49
  182. * @endcode
  183. *
  184. * **Response (success):**
  185. * @code
  186. * {
  187. * "revoked":true,
  188. * }
  189. * @endcode
  190. *
  191. * **Response (error):**
  192. * @code
  193. * {
  194. * "error":"short error description here",
  195. * "error_description":"long error description here"
  196. * }
  197. * @endcode
  198. */
  199. function actionRevoke ()
  200. {
  201. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  202. $this->_oServer->handleRevokeRequest(OAuth2\Request::createFromGlobals())->send();
  203. }
  204. /**
  205. * Authenicated or public call to the "safe" and "public" service methods
  206. */
  207. function actionCom ($sMethod)
  208. {
  209. if (!$this->_oAPI) {
  210. bx_import('API', $this->_aModule);
  211. $this->_oAPI = new BxOAuthAPI($this);
  212. }
  213. $bPublic = $this->_oAPI->isPublicAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod, bx_get('class') ? bx_get('class') : false);
  214. if ($bPublic) {
  215. if (!$this->_oDb->getClientsBy(array('type' => 'client_id', 'client_id' => bx_get('client_id')))) {
  216. $this->_oAPI->errorOutput(403, 'access_denied', '"public" services need valid "client_id" parameter');
  217. return;
  218. }
  219. $this->checkAllowedOrigins();
  220. $this->_oAPI->com($sMethod, array(), $bPublic);
  221. }
  222. else {
  223. if (!$this->_oAPI->isSafeAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod, bx_get('class') ? bx_get('class') : false)) {
  224. $this->_oAPI->errorOutput(403, 'access_denied', 'Only "public" and "safe" services can be called, or method doesn\'t exist');
  225. return;
  226. }
  227. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  228. // Handle a request to a resource and authenticate the access token
  229. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  230. $this->_oServer->getResponse()->send();
  231. return;
  232. }
  233. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  234. $aScope = explode(',', $this->_oAPI->aAction2Scope['api']);
  235. $aScopeToken = explode(',', $aToken['scope']);
  236. if (!array_intersect($aScopeToken, $aScope)) {
  237. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  238. return;
  239. }
  240. $this->_oAPI->com($sMethod, $aToken, false);
  241. }
  242. }
  243. /**
  244. * Authenicated call to the API
  245. */
  246. function actionApi ($sAction)
  247. {
  248. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  249. // Handle a request to a resource and authenticate the access token
  250. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  251. $this->_oServer->getResponse()->send();
  252. return;
  253. }
  254. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  255. if (!$this->_oAPI) {
  256. bx_import('API', $this->_aModule);
  257. $this->_oAPI = new BxOAuthAPI($this);
  258. }
  259. if (!$sAction || !method_exists($this->_oAPI, $sAction) || in_array($sAction, $this->_oAPI->aExceptionsAPI)) {
  260. $this->_oAPI->errorOutput(404, 'not_found', 'No such API endpoint available');
  261. return;
  262. }
  263. $aScope = explode(',', $this->_oAPI->aAction2Scope[$sAction]);
  264. $aScopeToken = explode(',', $aToken['scope']);
  265. if (!array_intersect($aScopeToken, $aScope)) {
  266. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  267. return;
  268. }
  269. $this->_oAPI->$sAction($aToken);
  270. }
  271. function actionAuth ()
  272. {
  273. $this->initOAuth(bx_get('client_id'));
  274. $oRequest = OAuth2\Request::createFromGlobals();
  275. $oResponse = new OAuth2\Response();
  276. // validate the authorize request
  277. if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
  278. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  279. $o = json_decode($oResponse->getResponseBody());
  280. $this->_oTemplate->getPage(false, MsgBox($o->error_description));
  281. }
  282. if (!isLogged()) {
  283. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  284. $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');
  285. bx_login_form(false, false, $sForceRelocate);
  286. return;
  287. }
  288. $aProfiles = BxDolAccount::getInstance()->getProfiles();
  289. if (1 == count($aProfiles)) { // in case of one profile, don't display dialog with profiles choice
  290. $aProfile = array_pop($aProfiles);
  291. $_POST['profile_id'] = $aProfile['id'];
  292. }
  293. if (!($iProfileId = $this->_oDb->getSavedProfile(bx_get('client_id'), $aProfiles)) && empty($_POST)) {
  294. $oPage = BxDolPage::getObjectInstanceByURI('oauth-authorization');
  295. $this->_oTemplate->getPage(false, $oPage->getCode());
  296. return;
  297. }
  298. if (!$iProfileId)
  299. $iProfileId = bx_get('profile_id');
  300. $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool)$iProfileId, $iProfileId);
  301. $oResponse->send();
  302. }
  303. function serviceAuthorization ()
  304. {
  305. $sTitle = $this->_oDb->getClientTitle(bx_get('client_id'));
  306. $this->_oTemplate->addCss('main.css');
  307. return $this->_oTemplate->parseHtmlByName('page_auth.html', array(
  308. 'text' => _t('_bx_oauth_authorize_app', htmlspecialchars_adv($sTitle)),
  309. 'url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth',
  310. 'client_id' => bx_get('client_id'),
  311. 'response_type' => bx_get('response_type'),
  312. 'redirect_uri' => bx_get('redirect_uri'),
  313. 'scope' => bx_get('scope'),
  314. 'state' => bx_get('state'),
  315. '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'],
  316. ));
  317. }
  318. function serviceGetClientsBy ($aParams = array())
  319. {
  320. return $this->_oDb->getClientsBy($aParams);
  321. }
  322. function serviceAddClient ($aClient)
  323. {
  324. if (!isset($aClient['client_id'])) {
  325. bx_import('FormAdd', 'bx_oauth');
  326. for ($i = 0; $i < 99 ; ++$i) {
  327. $aClient['client_id'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_ID, false));
  328. if (!$this->_oDb->getClientTitle($aClient['client_id'])) // check for uniq
  329. break;
  330. }
  331. }
  332. if (!isset($aClient['client_secret'])) {
  333. bx_import('FormAdd', 'bx_oauth');
  334. $aClient['client_secret'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_SECRET, false));
  335. }
  336. if (!isset($aClient['scope']))
  337. $aClient['scope'] = 'market';
  338. if (!isset($aClient['user_id']))
  339. $aClient['user_id'] = bx_get_logged_profile_id();
  340. if (!isset($aClient['title']) && isset($aClient['redirect_uri']) && ($sHost = parse_url($aClient['redirect_uri'], PHP_URL_HOST)))
  341. $aClient['title'] = $sHost;
  342. return $this->_oDb->addClient($aClient);
  343. }
  344. function serviceUpdateClientsBy ($aParamsSet, $aParamsWhere)
  345. {
  346. return $this->_oDb->updateClientsBy($aParamsSet, $aParamsWhere);
  347. }
  348. function serviceDeleteClientsBy ($aParams)
  349. {
  350. return $this->_oDb->deleteClientsBy($aParams);
  351. }
  352. function studioSettings ()
  353. {
  354. if (!isAdmin()) {
  355. $this->_oTemplate->displayAccessDenied ();
  356. return;
  357. }
  358. $oGrid = BxDolGrid::getObjectInstance('bx_oauth', BxDolStudioTemplate::getInstance());
  359. if ($oGrid)
  360. return $oGrid->getCode();
  361. return '';
  362. }
  363. function getClientIdFromAccessTokenHeader()
  364. {
  365. if (isset($_SERVER['HTTP_AUTHORIZATION']))
  366. $sAuthHeader = $_SERVER['HTTP_AUTHORIZATION'];
  367. elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
  368. $sAuthHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
  369. if (empty($sAuthHeader))
  370. return false;
  371. if (false === stripos($sAuthHeader, 'Bearer'))
  372. return false;
  373. return $this->_oDb->getClientIdByAccessToken(trim(substr($sAuthHeader, 6)));
  374. }
  375. }
  376. /** @} */