BxOktaConModule.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 OktaConnect Okta Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. /**
  12. * This Okta connect code was created with instructions from:
  13. * https://developer.okta.com/docs/guides/implement-oauth-for-okta/main/
  14. */
  15. class BxOktaConModule extends BxBaseModConnectModule
  16. {
  17. function __construct(&$aModule)
  18. {
  19. parent::__construct($aModule);
  20. }
  21. /**
  22. * Redirect to remote site login form
  23. *
  24. * @return n/a - redirect or HTML page in case of error
  25. */
  26. function actionStart()
  27. {
  28. if (isset($_GET["error"])) {
  29. $this->_oTemplate->getPage(_t($this->_oConfig->sDefaultTitleLangKey), DesignBoxContent(_t($this->_oConfig->sDefaultTitleLangKey), MsgBox(bx_get('error'))));
  30. exit;
  31. }
  32. if (isLogged()) {
  33. $this->_redirect ($this -> _oConfig -> sDefaultRedirectUrl);
  34. }
  35. if (!$this->_oConfig->sClientID || !$this->_oConfig->sSecret || !$this->_oConfig->sDomain) {
  36. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  37. bx_import('BxDolLanguages');
  38. $sCode = MsgBox( _t('_bx_oktacon_profile_error_api_keys') );
  39. $this->_oTemplate->getPage(_t('_bx_oktacon'), $sCode);
  40. }
  41. else {
  42. // First stage of the authentication process; This is just a simple redirect (first load of this page)
  43. $sUrl = bx_append_url_params("https://{$this->_oConfig->sDomain}/oauth2/default/v1/authorize", [
  44. 'state' => $this->_genToken(), // BxDolSession::getInstance()->getId(), // This at least semi-random string is likely good enough as state identifier
  45. 'scope' => $this->_oConfig->sScope,
  46. 'response_type' => 'code',
  47. 'response_mode' => 'query',
  48. 'client_id' => $this->_oConfig->sClientID,
  49. 'redirect_uri' => $this->_oConfig->sPageHandle,
  50. ]);
  51. $this->_redirect($sUrl);
  52. }
  53. }
  54. function actionHandle()
  55. {
  56. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  57. // check CSRF token
  58. if ($this->_getToken() != bx_get('state')) {
  59. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  60. return;
  61. }
  62. // check code
  63. $sCode = bx_get('code');
  64. if (!$sCode || bx_get('error')) {
  65. $sErrorDescription = bx_get('error_description') ? bx_get('error_description') : _t('_error occured');
  66. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  67. return;
  68. }
  69. $s = bx_file_get_contents("https://{$this->_oConfig->sDomain}/oauth2/default/v1/token", [
  70. 'grant_type' => 'authorization_code',
  71. 'client_id' => $this->_oConfig->sClientID,
  72. 'redirect_uri' => $this->_oConfig->sPageHandle,
  73. 'code' => $sCode,
  74. 'client_secret' => $this->_oConfig->sSecret,
  75. ], 'post', array ('Content-Type: application/x-www-form-urlencoded'));
  76. $aAuthData = $this->_decodeResponseAndHandleError($s);
  77. $aRemoteProfileInfo = [];
  78. if ($this->_oConfig->bGetUserInfoFromIdToken) {
  79. $aRemoteProfileInfo = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $aAuthData['id_token'])[1]))), true);
  80. }
  81. else {
  82. // get the data, especially access_token
  83. $sAccessToken = $aAuthData['access_token'];
  84. $sExpiresIn = $aAuthData['expires_in'];
  85. $sExpiresAt = new \DateTime('+' . $sExpiresIn . ' seconds');
  86. // request info about profile
  87. $s = bx_file_get_contents("https://{$this->_oConfig->sDomain}/oauth2/default/v1/userinfo", array(), 'get', array(
  88. 'Accept: application/json',
  89. 'Authorization: Bearer ' . $sAccessToken,
  90. ));
  91. $aRemoteProfileInfo = $this->_decodeResponseAndHandleError($s);
  92. }
  93. $aRemoteProfileInfo['id'] = $aRemoteProfileInfo[$this->_oConfig->sUserIdField];
  94. /*
  95. // request profile photo
  96. $s = bx_file_get_contents("https://graph.microsoft.com/v1.0/me/photo/", array(), 'get', array(
  97. 'Accept: application/json',
  98. 'Authorization: Bearer ' . $sAccessToken,
  99. ));
  100. $aUserPhoto = $this->_decodeResponseAndHandleError($s, false);
  101. $aRemoteProfileInfo['picture'] = $aUserPhoto;
  102. */
  103. if ($aRemoteProfileInfo) {
  104. // check if user logged in before
  105. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  106. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  107. // user already exists
  108. $this->setLogged($oProfile->id(), '', true, getParam('bx_oktacon_remember_session')); // remember user
  109. bx_import('Custom', $this->_aModule);
  110. $oCustom = new BxOktaConCustom($this->_aModule);
  111. $oCustom->onLogin($oProfile, $aRemoteProfileInfo);
  112. }
  113. else {
  114. // register new user
  115. $this->_createProfile($aRemoteProfileInfo);
  116. }
  117. }
  118. else {
  119. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  120. }
  121. }
  122. function _createProfileRaw($aProfileInfo, $sAlternativeName = '', $isAutoFriends = true, $isSetLoggedIn = true)
  123. {
  124. $mixed = parent::_createProfileRaw($aProfileInfo, $sAlternativeName, $isAutoFriends, $isSetLoggedIn);
  125. if (is_array($mixed) && isset($mixed['profile_id']) && (!isset($mixed['join_page_redirect']) || !$mixed['join_page_redirect'])) {
  126. bx_import('Custom', $this->_aModule);
  127. $oCustom = new BxOktaConCustom($this->_aModule);
  128. $oCustom->onRegister($mixed['profile_id'], $aProfileInfo);
  129. }
  130. return $mixed;
  131. }
  132. /**
  133. * @param $aProfileInfo - remote profile info
  134. * @param $sAlternativeName - suffix to add to NickName to make it unique
  135. * @return profile array info, ready for the local database
  136. */
  137. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  138. {
  139. $aProfileFields = $aProfileInfo;
  140. $sName = !empty($aProfileInfo['name']) ? $aProfileInfo['name'] : $aProfileInfo[$this->_oConfig->sUserIdField];
  141. $aProfileFields['name'] = !empty($aProfileInfo['preferred_username']) ? $aProfileInfo['preferred_username'] : $sName;
  142. $aProfileFields['fullname'] = $sName; // !empty($aProfileInfo['given_name']) ? $aProfileInfo['given_name'] : $aProfileFields['name'];
  143. $aProfileFields['last_name'] = !empty($aProfileInfo['family_name']) ? ' ' . $aProfileInfo['family_name'] : '';
  144. $aProfileFields['email'] = isset($aProfileInfo['email']) ? $aProfileInfo['email'] : '';
  145. $aProfileFields['picture'] = '';
  146. $aProfileFields['allow_view_to'] = getParam('bx_oktacon_privacy');
  147. bx_import('Custom', $this->_aModule);
  148. $oCustom = new BxOktaConCustom($this->_aModule);
  149. $oCustom->onConvertRemoteFields($aProfileInfo, $aProfileFields);
  150. return $aProfileFields;
  151. }
  152. protected function _decodeResponseAndHandleError($s, $bDisplayErrorPage = true)
  153. {
  154. if (!$s || NULL === ($aData = json_decode($s, true)) || !$aData || isset($aData['error'])) {
  155. if (is_array($aData['error']) && !empty($aData['error']['message']))
  156. $sErrorDescription = $aData['error']['message'];
  157. else
  158. $sErrorDescription = isset($aData['error_description']) ? $aData['error_description'] : _t('_error occured');
  159. if ($bDisplayErrorPage) {
  160. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  161. exit;
  162. }
  163. else {
  164. return false;
  165. }
  166. }
  167. return $aData;
  168. }
  169. protected function _getExistingAccount($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  170. {
  171. if ($this->_oConfig->bAddExtensionsForDuplicateEmails) {
  172. $i = 1;
  173. while (BxDolAccount::getInstance($aFieldsAccount['email'])) {
  174. $aFieldsAccount['email'] = preg_replace('/(.*?)(\+\d+)?@(.*?)/', '$1+' . $i . '@$3', $aFieldsAccount['email']);
  175. ++$i;
  176. }
  177. return false;
  178. }
  179. else {
  180. return BxDolAccount::getInstance($aFieldsAccount['email']);
  181. }
  182. }
  183. function serviceLogin($sRemoteId)
  184. {
  185. $iProfileId = $this->_oDb->getProfileId($sRemoteId);
  186. if (!$iProfileId || !($oProfile = BxDolProfile::getInstance($iProfileId)))
  187. return false;
  188. $bRememberMe = false;
  189. bx_login($oProfile->getAccountId(), $bRememberMe);
  190. $aRet = $this->getUserIds($oProfile);
  191. $aRet['session'] = BxDolSession::getInstance()->getId();
  192. return $aRet;
  193. }
  194. function serviceGetUserIds($sRemoteId)
  195. {
  196. $iProfileId = $this->_oDb->getProfileId($sRemoteId);
  197. if (!$iProfileId || !($oProfile = BxDolProfile::getInstance($iProfileId)))
  198. return false;
  199. return $this->getUserIds($oProfile);
  200. }
  201. protected function getUserIds($oProfile)
  202. {
  203. return [
  204. 'account_id' => $oProfile->getAccountId(),
  205. 'profile_id' => $oProfile->id(),
  206. 'content_id' => $oProfile->getContentId(),
  207. 'content_module' => $oProfile->getModule(),
  208. ];
  209. }
  210. }
  211. /** @} */