BxOAuthModule.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. * Authenicated or public call to the "safe" and "public" service methods
  160. */
  161. function actionCom ($sMethod)
  162. {
  163. if (!$this->_oAPI) {
  164. bx_import('API', $this->_aModule);
  165. $this->_oAPI = new BxOAuthAPI($this);
  166. }
  167. $bPublic = $this->_oAPI->isPublicAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod);
  168. if ($bPublic) {
  169. $this->checkAllowedOrigins();
  170. $this->_oAPI->com($sMethod, array(), $bPublic);
  171. }
  172. else {
  173. if (!$this->_oAPI->isSafeAPI(bx_get('module') ? bx_get('module') : 'bx_api', $sMethod)) {
  174. $this->_oAPI->errorOutput(403, 'access_denied', 'Only "public" and "safe" services can be called, or method doesn\'t exist');
  175. return;
  176. }
  177. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  178. // Handle a request to a resource and authenticate the access token
  179. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  180. $this->_oServer->getResponse()->send();
  181. return;
  182. }
  183. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  184. $aScope = explode(',', $this->_oAPI->aAction2Scope['api']);
  185. $aScopeToken = explode(',', $aToken['scope']);
  186. if (!array_intersect($aScopeToken, $aScope)) {
  187. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  188. return;
  189. }
  190. $this->_oAPI->com($sMethod, $aToken, false);
  191. }
  192. }
  193. /**
  194. * Authenicated call to the API
  195. */
  196. function actionApi ($sAction)
  197. {
  198. $this->initOAuth($this->getClientIdFromAccessTokenHeader());
  199. // Handle a request to a resource and authenticate the access token
  200. if (!$this->_oServer->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
  201. $this->_oServer->getResponse()->send();
  202. return;
  203. }
  204. $aToken = $this->_oServer->getAccessTokenData(OAuth2\Request::createFromGlobals());
  205. if (!$this->_oAPI) {
  206. bx_import('API', $this->_aModule);
  207. $this->_oAPI = new BxOAuthAPI($this);
  208. }
  209. if (!$sAction || !method_exists($this->_oAPI, $sAction) || in_array($sAction, $this->_oAPI->aExceptionsAPI)) {
  210. $this->_oAPI->errorOutput(404, 'not_found', 'No such API endpoint available');
  211. return;
  212. }
  213. $aScope = explode(',', $this->_oAPI->aAction2Scope[$sAction]);
  214. $aScopeToken = explode(',', $aToken['scope']);
  215. if (!array_intersect($aScopeToken, $aScope)) {
  216. $this->_oAPI->errorOutput(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
  217. return;
  218. }
  219. $this->_oAPI->$sAction($aToken);
  220. }
  221. function actionAuth ()
  222. {
  223. $this->initOAuth(bx_get('client_id'));
  224. $oRequest = OAuth2\Request::createFromGlobals();
  225. $oResponse = new OAuth2\Response();
  226. // validate the authorize request
  227. if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
  228. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  229. $o = json_decode($oResponse->getResponseBody());
  230. $this->_oTemplate->getPage(false, MsgBox($o->error_description));
  231. }
  232. if (!isLogged()) {
  233. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  234. $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');
  235. bx_login_form(false, false, $sForceRelocate);
  236. return;
  237. }
  238. $aProfiles = BxDolAccount::getInstance()->getProfiles();
  239. if (1 == count($aProfiles)) { // in case of one profile, don't display dialog with profiles choice
  240. $aProfile = array_pop($aProfiles);
  241. $_POST['profile_id'] = $aProfile['id'];
  242. }
  243. if (!($iProfileId = $this->_oDb->getSavedProfile(bx_get('client_id'), $aProfiles)) && empty($_POST)) {
  244. $oPage = BxDolPage::getObjectInstanceByURI('oauth-authorization');
  245. $this->_oTemplate->getPage(false, $oPage->getCode());
  246. return;
  247. }
  248. if (!$iProfileId)
  249. $iProfileId = bx_get('profile_id');
  250. $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool)$iProfileId, $iProfileId);
  251. $oResponse->send();
  252. }
  253. function serviceAuthorization ()
  254. {
  255. $sTitle = $this->_oDb->getClientTitle(bx_get('client_id'));
  256. $this->_oTemplate->addCss('main.css');
  257. return $this->_oTemplate->parseHtmlByName('page_auth.html', array(
  258. 'text' => _t('_bx_oauth_authorize_app', htmlspecialchars_adv($sTitle)),
  259. 'url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth',
  260. 'client_id' => bx_get('client_id'),
  261. 'response_type' => bx_get('response_type'),
  262. 'redirect_uri' => bx_get('redirect_uri'),
  263. 'scope' => bx_get('scope'),
  264. 'state' => bx_get('state'),
  265. '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'],
  266. ));
  267. }
  268. function serviceGetClientsBy ($aParams = array())
  269. {
  270. return $this->_oDb->getClientsBy($aParams);
  271. }
  272. function serviceAddClient ($aClient)
  273. {
  274. if (!isset($aClient['client_id'])) {
  275. bx_import('FormAdd', 'bx_oauth');
  276. for ($i = 0; $i < 99 ; ++$i) {
  277. $aClient['client_id'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_ID, false));
  278. if (!$this->_oDb->getClientTitle($aClient['client_id'])) // check for uniq
  279. break;
  280. }
  281. }
  282. if (!isset($aClient['client_secret'])) {
  283. bx_import('FormAdd', 'bx_oauth');
  284. $aClient['client_secret'] = strtolower(genRndPwd(BxOAuthFormAdd::$LENGTH_SECRET, false));
  285. }
  286. if (!isset($aClient['scope']))
  287. $aClient['scope'] = 'market';
  288. if (!isset($aClient['user_id']))
  289. $aClient['user_id'] = bx_get_logged_profile_id();
  290. if (!isset($aClient['title']) && isset($aClient['redirect_uri']) && ($sHost = parse_url($aClient['redirect_uri'], PHP_URL_HOST)))
  291. $aClient['title'] = $sHost;
  292. return $this->_oDb->addClient($aClient);
  293. }
  294. function serviceUpdateClientsBy ($aParamsSet, $aParamsWhere)
  295. {
  296. return $this->_oDb->updateClientsBy($aParamsSet, $aParamsWhere);
  297. }
  298. function serviceDeleteClientsBy ($aParams)
  299. {
  300. return $this->_oDb->deleteClientsBy($aParams);
  301. }
  302. function studioSettings ()
  303. {
  304. if (!isAdmin()) {
  305. $this->_oTemplate->displayAccessDenied ();
  306. return;
  307. }
  308. $oGrid = BxDolGrid::getObjectInstance('bx_oauth', BxDolStudioTemplate::getInstance());
  309. if ($oGrid)
  310. return $oGrid->getCode();
  311. return '';
  312. }
  313. function getClientIdFromAccessTokenHeader()
  314. {
  315. if (isset($_SERVER['HTTP_AUTHORIZATION']))
  316. $sAuthHeader = $_SERVER['HTTP_AUTHORIZATION'];
  317. elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
  318. $sAuthHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
  319. if (empty($sAuthHeader))
  320. return false;
  321. if (false === stripos($sAuthHeader, 'Bearer'))
  322. return false;
  323. return $this->_oDb->getClientIdByAccessToken(trim(substr($sAuthHeader, 6)));
  324. }
  325. }
  326. /** @} */