BxCidaasConModule.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 CidaasConnect Cidaas Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. require_once(BX_DIRECTORY_PATH_MODULES . 'boonex/cidaas_connect/vendor/autoload.php');
  12. use Cidaas\OAuth2\Client\Provider\GrantType;
  13. use GuzzleHttp\Exception\ClientException;
  14. /**
  15. * Login via the official Cidaas PHP SDK hosted login page.
  16. * @see https://github.com/cidaas/cidaas-sdk-php
  17. */
  18. class BxCidaasConModule extends BxBaseModConnectModule
  19. {
  20. function __construct(&$aModule)
  21. {
  22. parent::__construct($aModule);
  23. }
  24. public function actionLogout()
  25. {
  26. if (!isLogged())
  27. return;
  28. echo "TODO: logout";
  29. }
  30. /**
  31. * This service need to be called when we call logout from UNA,
  32. * so it will propagate logout to IDP
  33. * Other words: logout in UNA, IDP and all other SP
  34. */
  35. public function serviceLogout()
  36. {
  37. if (!isLogged())
  38. return;
  39. $sAccessToken = BxDolSession::getInstance()->getUnsetValue('cidaascon_access_token');
  40. if (!$sAccessToken)
  41. return;
  42. try {
  43. $this->_getProvider()->logout($sAccessToken)->wait();
  44. } catch (Exception $oException) {
  45. bx_log('bx_cidaas', $this->_getExceptionMessage($oException));
  46. }
  47. }
  48. /**
  49. * Redirect to Cidaas hosted login page.
  50. *
  51. * @return n/a - redirect or HTML page in case of error
  52. */
  53. function actionStart()
  54. {
  55. if (isset($_GET['error'])) {
  56. $this->_oTemplate->getPage(_t($this->_oConfig->sDefaultTitleLangKey), DesignBoxContent(_t($this->_oConfig->sDefaultTitleLangKey), MsgBox(bx_get('error'))));
  57. exit;
  58. }
  59. if (isLogged()) {
  60. $this->_redirect($this->_oConfig->sDefaultRedirectUrl);
  61. }
  62. if (!$this->_oConfig->sBaseUrl || !$this->_oConfig->sClientID || (!$this->_oConfig->bPkce && !$this->_oConfig->sSecret)) {
  63. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  64. bx_import('BxDolLanguages');
  65. $sCode = MsgBox(_t('_bx_cidaascon_profile_error_api_keys'));
  66. $this->_oTemplate->getPage(_t('_bx_cidaascon'), $sCode);
  67. return;
  68. }
  69. try {
  70. $this->_getProvider()->loginWithBrowser($this->_oConfig->sScope, [
  71. 'state' => $this->_genToken(),
  72. ], $this->_oConfig->bPkce);
  73. } catch (Exception $oException) {
  74. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  75. $this->_oTemplate->getPage(_t('_Error'), MsgBox($this->_getExceptionMessage($oException)));
  76. return;
  77. }
  78. // SDK stores the PKCE verifier in PHP $_SESSION; persist it in UNA session for the callback.
  79. if ($this->_oConfig->bPkce && !empty($_SESSION['code-verifier']))
  80. BxDolSession::getInstance()->setValue($this->_oConfig->sSessionCodeVerifier, $_SESSION['code-verifier']);
  81. exit;
  82. }
  83. /**
  84. * $aAuthData = [
  85. * [access_token] => eyJhbGciOiJSUz...
  86. * [id_token] => eyJhbGciOiJS...
  87. * [state] => TkkLRS6wp4ukNyEzPhZi
  88. * [expires_in] => 86400
  89. * [id_token_expires_in] => 86400
  90. * [token_type] => Bearer
  91. * [sub] => 21xxxxxx-9da8-4fd9-ad14-e5f3c615f55a
  92. * [sid] => c5xxxxxx-a54a-403e-b237-99c728059cc6
  93. * [identity_id] => 74e3bf36-d1d7-4e4c-a95b-5822abfc6b97
  94. * ]
  95. * @return void
  96. */
  97. function actionHandle()
  98. {
  99. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  100. try {
  101. $oProvider = $this->_getProvider();
  102. } catch (Exception $oException) {
  103. $this->_oTemplate->getPage(_t('_Error'), MsgBox($this->_getExceptionMessage($oException)));
  104. return;
  105. }
  106. $aParameters = $oProvider->loginCallback();
  107. if ($this->_getToken() != ($aParameters['state'] ?? '')) {
  108. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  109. return;
  110. }
  111. $sCode = $aParameters['code'] ?? '';
  112. if (!$sCode || !empty($aParameters['error'])) {
  113. $sErrorDescription = !empty($aParameters['error_description']) ? $aParameters['error_description'] : (!empty($aParameters['error']) ? $aParameters['error'] : _t('_error occured'));
  114. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  115. return;
  116. }
  117. if ($this->_oConfig->bPkce) {
  118. $sCodeVerifier = BxDolSession::getInstance()->getUnsetValue($this->_oConfig->sSessionCodeVerifier);
  119. if ($sCodeVerifier)
  120. $_SESSION['code-verifier'] = $sCodeVerifier;
  121. }
  122. try {
  123. $aAuthData = $oProvider->getAccessToken(GrantType::AuthorizationCode, $sCode, '', $this->_oConfig->bPkce)->wait();
  124. if (empty($aAuthData['access_token'])) {
  125. $sErrorDescription = isset($aAuthData['error_description']) ? $aAuthData['error_description'] : _t('_error occured');
  126. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  127. return;
  128. }
  129. BxDolSession::getInstance()->setValue('cidaascon_access_token', $aAuthData['access_token']);
  130. $aRemoteProfileInfo = $oProvider->getUserProfile($aAuthData['access_token'])->wait();
  131. } catch (Exception $oException) {
  132. $this->_oTemplate->getPage(_t('_Error'), MsgBox($this->_getExceptionMessage($oException)));
  133. return;
  134. }
  135. if (isset($aRemoteProfileInfo['data']) && is_array($aRemoteProfileInfo['data']))
  136. $aRemoteProfileInfo = $aRemoteProfileInfo['data'];
  137. if (empty($aRemoteProfileInfo['id']) && !empty($aRemoteProfileInfo['sub']))
  138. $aRemoteProfileInfo['id'] = $aRemoteProfileInfo['sub'];
  139. if ($aRemoteProfileInfo && !empty($aRemoteProfileInfo['id'])) {
  140. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  141. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  142. $this->setLogged($oProfile->id(), '', true, true);
  143. }
  144. else {
  145. $this->_createProfile($aRemoteProfileInfo);
  146. }
  147. }
  148. else {
  149. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  150. }
  151. }
  152. public function serviceGetSafeServices()
  153. {
  154. return array_merge(parent::serviceGetSafeServices(), [
  155. 'Handle' => '',
  156. ]);
  157. }
  158. public function serviceHandle($aRemoteProfileInfo = [])
  159. {
  160. if (!$this->_bIsApi)
  161. return;
  162. if (is_string($aRemoteProfileInfo))
  163. $aRemoteProfileInfo = bx_api_get_browse_params($aRemoteProfileInfo);
  164. if (empty($aRemoteProfileInfo) || !is_array($aRemoteProfileInfo))
  165. return [
  166. bx_api_get_msg(_t('_sys_connect_profile_error_info'))
  167. ];
  168. if (empty($aRemoteProfileInfo['id']) && !empty($aRemoteProfileInfo['sub']))
  169. $aRemoteProfileInfo['id'] = $aRemoteProfileInfo['sub'];
  170. $iProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  171. if ($iProfileId && $oProfile = BxDolProfile::getInstance($iProfileId))
  172. return $this->setLogged($oProfile->id());
  173. else
  174. return $this->_createProfile($aRemoteProfileInfo);
  175. }
  176. /**
  177. *
  178. * (
  179. * [last_used_identity_id] => 74e3bf36-d1d7-4e4c-a95b-5822abfc6b97
  180. * [sub] => 21e029a8-9da8-4fd9-ad14-e5f3c615f55a
  181. * [updated_at] => 1787238995
  182. * [createdTime] => 2026-08-20T15:16:35.513Z
  183. * [userStatus] => VERIFIED
  184. * [lastLoggedInTime] => 2026-08-24T10:05:34.3Z
  185. * [customFields] => Array
  186. * (
  187. * [city] => Sydney
  188. * [department] => Support
  189. * [job_title] => Support
  190. * [name_of_company] => UNA Inc
  191. * [other_interests] => IT
  192. * [responsibilty] => Support
  193. * )
  194. *
  195. * [email] => team@unacms.com
  196. * [email_verified] => 1
  197. * [provider] => self
  198. * [given_name] => UNA
  199. * [family_name] => Team
  200. * [address] => Array
  201. * (
  202. * [country] => Australia
  203. * )
  204. *
  205. * [user_status] => VERIFIED
  206. * [name] => UNA Team
  207. * [last_accessed_at] => 1787565934
  208. * )
  209. *
  210. * @param $aProfileInfo - remote profile info
  211. * @param $sAlternativeName - suffix to add to NickName to make it unique
  212. * @return profile array info, ready for the local database
  213. */
  214. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  215. {
  216. $aProfileFields = $aProfileInfo;
  217. $sEmail = !empty($aProfileInfo['email']) ? $aProfileInfo['email'] : '';
  218. if (!$sEmail && !empty($aProfileInfo['identities'][0]['email']))
  219. $sEmail = $aProfileInfo['identities'][0]['email'];
  220. $sName = !empty($aProfileInfo['preferred_username']) ? $aProfileInfo['preferred_username'] : '';
  221. if (!$sName && !empty($aProfileInfo['name']))
  222. $sName = $aProfileInfo['name'];
  223. if (!$sName && !empty($aProfileInfo['given_name']))
  224. $sName = $aProfileInfo['given_name'];
  225. if (!$sName && $sEmail)
  226. $sName = explode('@', $sEmail)[0];
  227. if (!$sName)
  228. $sName = !empty($aProfileInfo['sub']) ? $aProfileInfo['sub'] : '';
  229. $sFullname = !empty($aProfileInfo['name']) ? $aProfileInfo['name'] : trim((!empty($aProfileInfo['given_name']) ? $aProfileInfo['given_name'] : '') . ' ' . (!empty($aProfileInfo['family_name']) ? $aProfileInfo['family_name'] : ''));
  230. if (!$sFullname)
  231. $sFullname = $sName;
  232. $aProfileFields['name'] = $sName;
  233. $aProfileFields['fullname'] = $sFullname;
  234. $aProfileFields['first_name'] = !empty($aProfileInfo['given_name']) ? $aProfileInfo['given_name'] : '';
  235. $aProfileFields['last_name'] = !empty($aProfileInfo['family_name']) ? $aProfileInfo['family_name'] : '';
  236. $aProfileFields['email'] = $sEmail;
  237. $aProfileFields['picture'] = !empty($aProfileInfo['picture']) ? $aProfileInfo['picture'] : '';
  238. $aProfileFields['allow_view_to'] = getParam('bx_cidaascon_privacy');
  239. return $aProfileFields;
  240. }
  241. /**
  242. * @return BxCidaasConProvider
  243. */
  244. protected function _getProvider()
  245. {
  246. bx_import('Provider', $this->_aModule);
  247. return new BxCidaasConProvider(
  248. $this->_oConfig->sBaseUrl,
  249. $this->_oConfig->sClientID,
  250. $this->_oConfig->sSecret ? $this->_oConfig->sSecret : '',
  251. $this->_oConfig->sPageHandle,
  252. null,
  253. $this->_oConfig->bDebug
  254. );
  255. }
  256. protected function _getExceptionMessage($oException)
  257. {
  258. if ($oException instanceof ClientException && $oException->hasResponse()) {
  259. $aBody = json_decode((string)$oException->getResponse()->getBody(), true);
  260. if (!empty($aBody['error']['error_description']))
  261. return $aBody['error']['error_description'];
  262. if (!empty($aBody['error_description']))
  263. return $aBody['error_description'];
  264. if (!empty($aBody['error']) && is_string($aBody['error']))
  265. return $aBody['error'];
  266. }
  267. $sMessage = $oException->getMessage();
  268. return $sMessage ? $sMessage : _t('_error occured');
  269. }
  270. }
  271. /** @} */