BxCidaasConModule.php 11 KB

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