sso.Drupal.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <?php
  2. use ChamiloSession as Session;
  3. /* For licensing terms, see /license.txt */
  4. /**
  5. * This file contains the necessary elements to implement a Single Sign On
  6. * mechanism with an external Drupal application (on which the Chamilo module
  7. * 7.x-1.0-alpha3 or above must be implemented)
  8. *
  9. * To use this class, set variable "sso_authentication_subclass" to "Drupal"
  10. * in Chamilo settings. If not yet available in the "Security" tab, execute the
  11. * following on the Chamilo database:
  12. * INSERT INTO `settings_current` (`variable`, `type`, `category`, `selected_value`, `title`, `comment`, `access_url`)
  13. * VALUES ('sso_authentication_subclass', 'textfield', 'Security', 'Drupal', 'SSOSubclass', 'SSOSubclassComment', 1);
  14. *
  15. * @package chamilo.auth.sso
  16. */
  17. /**
  18. * The SSO class allows for management of remote Single Sign On resources
  19. */
  20. class ssoDrupal
  21. {
  22. public $protocol; // 'http://',
  23. public $domain; // 'localhost/project/drupal',
  24. public $auth_uri; // '/?q=user',
  25. public $deauth_uri; // '/?q=logout',
  26. public $referer; // http://my.chamilo.com/main/auth/profile.php
  27. /**
  28. * Instanciates the object, initializing all relevant URL strings
  29. */
  30. public function __construct()
  31. {
  32. $this->protocol = api_get_setting('sso_authentication_protocol');
  33. // There can be multiple domains, so make sure to take only the first
  34. // This might be later extended with a decision process
  35. $domains = preg_split('/,/', api_get_setting('sso_authentication_domain'));
  36. $this->domain = trim($domains[0]);
  37. $this->auth_uri = api_get_setting('sso_authentication_auth_uri');
  38. $this->deauth_uri = api_get_setting('sso_authentication_unauth_uri');
  39. //cut the string to avoid recursive URL construction in case of failure
  40. $this->referer = $this->protocol.$_SERVER['HTTP_HOST'].substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], 'sso'));
  41. $this->deauth_url = $this->protocol.$this->domain.$this->deauth_uri;
  42. $this->master_url = $this->protocol.$this->domain.$this->auth_uri;
  43. $this->target = api_get_path(WEB_PATH);
  44. }
  45. /**
  46. * Unlogs the user from the remote server
  47. */
  48. public function logout()
  49. {
  50. if (empty($_GET['no_redirect'])) {
  51. header('Location: '.$this->deauth_url);
  52. } else {
  53. header('Location: '.$this->protocol.$this->domain);
  54. }
  55. exit;
  56. }
  57. /**
  58. * Sends the user to the master URL for a check of active connection
  59. */
  60. public function ask_master()
  61. {
  62. // Generate a single usage token that must be encoded by the master
  63. $_SESSION['sso_challenge'] = api_generate_password(48);
  64. // Redirect browser to the master URL
  65. $params = '';
  66. if (empty($_GET['no_redirect'])) {
  67. $params = 'sso_referer='.urlencode($this->referer).'&sso_target='.urlencode($this->target).'&sso_challenge='.urlencode($_SESSION['sso_challenge']);
  68. if (strpos($this->master_url, "?") === false) {
  69. $params = "?{$params}";
  70. } else {
  71. $params = "&{$params}";
  72. }
  73. }
  74. header('Location: '.$this->master_url.$params);
  75. exit;
  76. }
  77. /**
  78. * Validates the received active connection data with the database
  79. * @return bool Return the loginFailed variable value to local.inc.php
  80. */
  81. public function check_user()
  82. {
  83. global $_user;
  84. $loginFailed = false;
  85. //change the way we recover the cookie depending on how it is formed
  86. $sso = $this->decode_cookie($_GET['sso_cookie']);
  87. //get token that should have been used and delete it
  88. //from session since it can only be used once
  89. $sso_challenge = '';
  90. if (isset($_SESSION['sso_challenge'])) {
  91. $sso_challenge = $_SESSION['sso_challenge'];
  92. unset($_SESSION['sso_challenge']);
  93. }
  94. //lookup the user in the main database
  95. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  96. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
  97. FROM $user_table
  98. WHERE username = '".trim(Database::escape_string($sso['username']))."'";
  99. $result = Database::query($sql);
  100. if (Database::num_rows($result) > 0) {
  101. $uData = Database::fetch_array($result);
  102. //Check the user's password
  103. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  104. if ($sso['secret'] === sha1($uData['username'].$sso_challenge.api_get_security_key())
  105. && ($sso['username'] == $uData['username'])) {
  106. //Check if the account is active (not locked)
  107. if ($uData['active']=='1') {
  108. // check if the expiration date has not been reached
  109. if (empty($uData['expiration_date']) OR $uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {
  110. //If Multiple URL is enabled
  111. if (api_get_multiple_access_url()) {
  112. //Check the access_url configuration setting if the user is registered in the access_url_rel_user table
  113. //Getting the current access_url_id of the platform
  114. $current_access_url_id = api_get_current_access_url_id();
  115. // my user is subscribed in these
  116. //sites: $my_url_list
  117. $my_url_list = api_get_access_url_from_user($uData['user_id']);
  118. } else {
  119. $current_access_url_id = 1;
  120. $my_url_list = array(1);
  121. }
  122. $my_user_is_admin = UserManager::is_admin($uData['user_id']);
  123. if ($my_user_is_admin === false) {
  124. if (is_array($my_url_list) && count($my_url_list) > 0) {
  125. if (in_array($current_access_url_id, $my_url_list)) {
  126. // the user has permission to enter at this site
  127. $_user['user_id'] = $uData['user_id'];
  128. $_user = api_get_user_info($_user['user_id']);
  129. Session::write('_user', $_user);
  130. Event::event_login($_user['user_id']);
  131. // Redirect to homepage
  132. $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) . 'index.php';
  133. header('Location: '. $sso_target);
  134. exit;
  135. } else {
  136. // user does not have permission for this site
  137. $loginFailed = true;
  138. Session::erase('_uid');
  139. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  140. exit;
  141. }
  142. } else {
  143. // there is no URL in the multiple
  144. // urls list for this user
  145. $loginFailed = true;
  146. Session::erase('_uid');
  147. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  148. exit;
  149. }
  150. } else {
  151. //Only admins of the "main" (first) Chamilo
  152. // portal can login wherever they want
  153. if (in_array(1, $my_url_list)) {
  154. //Check if this admin is admin on the
  155. // principal portal
  156. $_user['user_id'] = $uData['user_id'];
  157. $_user = api_get_user_info($_user['user_id']);
  158. $is_platformAdmin = $uData['status'] == COURSEMANAGER;
  159. Session::write('is_platformAdmin', $is_platformAdmin);
  160. Session::write('_user', $_user);
  161. Event::event_login($_user['user_id']);
  162. } else {
  163. //Secondary URL admin wants to login
  164. // so we check as a normal user
  165. if (in_array($current_access_url_id, $my_url_list)) {
  166. $_user['user_id'] = $uData['user_id'];
  167. $_user = api_get_user_info($_user['user_id']);
  168. Session::write('_user', $_user);
  169. Event::event_login($_user['user_id']);
  170. } else {
  171. $loginFailed = true;
  172. Session::erase('_uid');
  173. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  174. exit;
  175. }
  176. }
  177. }
  178. } else {
  179. // user account expired
  180. $loginFailed = true;
  181. Session::erase('_uid');
  182. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_expired');
  183. exit;
  184. }
  185. } else {
  186. //User not active
  187. $loginFailed = true;
  188. Session::erase('_uid');
  189. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_inactive');
  190. exit;
  191. }
  192. } else {
  193. //SHA1 of password is wrong
  194. $loginFailed = true;
  195. Session::erase('_uid');
  196. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_password');
  197. exit;
  198. }
  199. } else {
  200. //Auth_source is wrong
  201. $loginFailed = true;
  202. Session::erase('_uid');
  203. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_authentication_source');
  204. exit;
  205. }
  206. } else {
  207. //No user by that login
  208. $loginFailed = true;
  209. Session::erase('_uid');
  210. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_not_found');
  211. exit;
  212. }
  213. return $loginFailed;
  214. }
  215. /**
  216. * Decode the cookie (this function may vary depending on the
  217. * Single Sign On implementation
  218. * @param string Encoded cookie
  219. * @return array Parsed and unencoded cookie
  220. */
  221. private function decode_cookie($cookie)
  222. {
  223. return unserialize(base64_decode($cookie));
  224. }
  225. /**
  226. * Generate the URL for profile editing for a any user or the current user
  227. * @param int $userId Optional. The user id
  228. * @param boolean $asAdmin Optional. Whether get the URL for the platform admin
  229. * @return string If the URL is obtained return the drupal_user_id. Otherwise return false
  230. */
  231. public function generateProfileEditingURL($userId = 0, $asAdmin = false)
  232. {
  233. $userId = intval($userId);
  234. if (empty($userId)) {
  235. $userId = api_get_user_id();
  236. }
  237. $userExtraFieldValue = new ExtraFieldValue('user');
  238. $drupalUserIdData = $userExtraFieldValue->get_values_by_handler_and_field_variable($userId, 'drupal_user_id');
  239. // If this is an administrator, allow him to make some changes in
  240. // the Chamilo profile
  241. if ($asAdmin && api_is_platform_admin(true)) {
  242. return api_get_path(WEB_CODE_PATH) . "admin/user_edit.php?user_id=$userId";
  243. }
  244. // If the user doesn't match a Drupal user, give the normal profile
  245. // link
  246. if ($drupalUserIdData === false) {
  247. return api_get_path(WEB_CODE_PATH) . 'auth/profile.php';
  248. }
  249. // In all other cases, generate a link to the Drupal profile edition
  250. $drupalUserId = $drupalUserIdData['field_value'];
  251. $url = "{$this->protocol}{$this->domain}/user/{$drupalUserId}/edit";
  252. return $url;
  253. }
  254. }