1
0

BxAzrConModule.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 AzureConnect Azure Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. /**
  12. * This Azude AD connect code was created with instructions from:
  13. * https://www.sipponen.com/archives/4024
  14. */
  15. class BxAzrConModule 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) {
  36. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  37. bx_import('BxDolLanguages');
  38. $sCode = MsgBox( _t('_bx_azrcon_profile_error_api_keys') );
  39. $this->_oTemplate->getPage(_t('_bx_azrcon'), $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://login.microsoftonline.com/" . $this->_oConfig->sTenantID . "/oauth2/v2.0/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, // User.Read scope seems to be enough, but you can try "&scope=profile+openid+email+offline_access+User.Read" if you like
  46. 'response_type' => 'code',
  47. 'approval_prompt' => 'auto',
  48. 'client_id' => $this->_oConfig->sClientID,
  49. 'redirect_uri' => $this->_oConfig->sPageHandle,
  50. ]);
  51. $this->_redirect($sUrl); // So off you go my dear browser and welcome back for round two after some redirects at Azure end
  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. // Verifying the received tokens with Azure and finalizing the authentication part
  70. $s = bx_file_get_contents("https://login.microsoftonline.com/" . $this->_oConfig->sTenantID . "/oauth2/v2.0/token", [
  71. 'grant_type' => 'authorization_code',
  72. 'client_id' => $this->_oConfig->sClientID,
  73. 'redirect_uri' => $this->_oConfig->sPageHandle,
  74. 'code' => $sCode,
  75. 'client_secret' => $this->_oConfig->sSecret,
  76. ], 'post', array ('Content-Type: application/x-www-form-urlencoded'));
  77. $aAuthData = $this->_decodeResponseAndHandleError($s);
  78. // get the data, especially access_token
  79. $sAccessToken = $aAuthData['access_token'];
  80. $sExpiresIn = $aAuthData['expires_in'];
  81. $sExpiresAt = new \DateTime('+' . $sExpiresIn . ' seconds');
  82. // request info about profile
  83. // In case you need some other attributes from the user object that are not coming with "/me" by default, you can use $select argument at line 74 to select the properties you really need:
  84. // https://graph.microsoft.com/v1.0/me?$select=givenName,surname,userPrincipalName,country
  85. $s = bx_file_get_contents("https://graph.microsoft.com/v1.0/me", array(), 'get', array(
  86. 'Accept: application/json',
  87. 'Authorization: Bearer ' . $sAccessToken,
  88. ));
  89. $aUserData = $this->_decodeResponseAndHandleError($s);
  90. // request profile photo
  91. $s = bx_file_get_contents("https://graph.microsoft.com/v1.0/me/photo/", array(), 'get', array(
  92. 'Accept: application/json',
  93. 'Authorization: Bearer ' . $sAccessToken,
  94. ));
  95. $aUserPhoto = $this->_decodeResponseAndHandleError($s, false);
  96. $aRemoteProfileInfo = $aUserData;
  97. $aRemoteProfileInfo['picture'] = $aUserPhoto;
  98. if ($aRemoteProfileInfo) {
  99. // check if user logged in before
  100. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  101. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  102. // user already exists
  103. $this->setLogged($oProfile ->id(), '', true, true); // remember user
  104. }
  105. else {
  106. // register new user
  107. $this->_createProfile($aRemoteProfileInfo);
  108. }
  109. }
  110. else {
  111. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  112. }
  113. }
  114. /**
  115. * @param $aProfileInfo - remote profile info
  116. * @param $sAlternativeName - suffix to add to NickName to make it unique
  117. * @return profile array info, ready for the local database
  118. */
  119. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  120. {
  121. $aProfileFields = $aProfileInfo;
  122. $a = explode('@', $aProfileInfo['userPrincipalName']);
  123. $sName = isset($a[0]) ? $a[0] : $aProfileInfo['userPrincipalName'];
  124. $aProfileFields['name'] = !empty($aProfileInfo['displayName']) ? $aProfileInfo['displayName'] : $sName;
  125. $aProfileFields['fullname'] = !empty($aProfileInfo['givenName']) ? $aProfileInfo['givenName'] : $aProfileFields['name'];
  126. $aProfileFields['last_name'] = !empty($aProfileInfo['surname']) ? ' ' . $aProfileInfo['surname'] : '';
  127. $aProfileFields['email'] = isset($aProfileInfo['mail']) ? $aProfileInfo['mail'] : $aProfileInfo['userPrincipalName'];
  128. $aProfileFields['picture'] = ''; // isset($aProfileInfo['picture']) ? $aProfileInfo['picture'] : '';
  129. $aProfileFields['allow_view_to'] = getParam('bx_azrcon_privacy');
  130. return $aProfileFields;
  131. }
  132. protected function _decodeResponseAndHandleError($s, $bDisplayErrorPage = true)
  133. {
  134. if (!$s || NULL === ($aData = json_decode($s, true)) || !$aData || isset($aData['error'])) {
  135. if (is_array($aData['error']) && !empty($aData['error']['message']))
  136. $sErrorDescription = $aData['error']['message'];
  137. else
  138. $sErrorDescription = isset($aData['error_description']) ? $aData['error_description'] : _t('_error occured');
  139. if ($bDisplayErrorPage) {
  140. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  141. exit;
  142. }
  143. else {
  144. return false;
  145. }
  146. }
  147. return $aData;
  148. }
  149. }
  150. /** @} */