BxOAuthModule.php 15 KB

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