BxOAuthModule.php 14 KB

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