sso.Drupal.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. header('Location: '.$this->deauth_url);
  51. exit;
  52. }
  53. /**
  54. * Sends the user to the master URL for a check of active connection
  55. */
  56. public function ask_master()
  57. {
  58. // Generate a single usage token that must be encoded by the master
  59. $_SESSION['sso_challenge'] = api_generate_password(48);
  60. // Redirect browser to the master URL
  61. $params = 'sso_referer='.urlencode($this->referer).'&sso_target='.urlencode($this->target).'&sso_challenge='.urlencode($_SESSION['sso_challenge']);
  62. if (strpos($this->master_url, "?") === false) {
  63. $params = "?{$params}";
  64. } else {
  65. $params = "&{$params}";
  66. }
  67. header('Location: '.$this->master_url.$params);
  68. exit;
  69. }
  70. /**
  71. * Validates the received active connection data with the database
  72. * @return bool Return the loginFailed variable value to local.inc.php
  73. */
  74. public function check_user()
  75. {
  76. global $_user;
  77. $loginFailed = false;
  78. //change the way we recover the cookie depending on how it is formed
  79. $sso = $this->decode_cookie($_GET['sso_cookie']);
  80. //get token that should have been used and delete it
  81. //from session since it can only be used once
  82. $sso_challenge = '';
  83. if (isset($_SESSION['sso_challenge'])) {
  84. $sso_challenge = $_SESSION['sso_challenge'];
  85. unset($_SESSION['sso_challenge']);
  86. }
  87. //lookup the user in the main database
  88. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  89. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
  90. FROM $user_table
  91. WHERE username = '".trim(Database::escape_string($sso['username']))."'";
  92. $result = Database::query($sql);
  93. if (Database::num_rows($result) > 0) {
  94. $uData = Database::fetch_array($result);
  95. //Check the user's password
  96. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  97. if ($sso['secret'] === sha1($uData['username'].$sso_challenge.api_get_security_key())
  98. && ($sso['username'] == $uData['username'])) {
  99. //Check if the account is active (not locked)
  100. if ($uData['active']=='1') {
  101. // check if the expiration date has not been reached
  102. if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {
  103. //If Multiple URL is enabled
  104. if (api_get_multiple_access_url()) {
  105. //Check the access_url configuration setting if the user is registered in the access_url_rel_user table
  106. //Getting the current access_url_id of the platform
  107. $current_access_url_id = api_get_current_access_url_id();
  108. // my user is subscribed in these
  109. //sites: $my_url_list
  110. $my_url_list = api_get_access_url_from_user($uData['user_id']);
  111. } else {
  112. $current_access_url_id = 1;
  113. $my_url_list = array(1);
  114. }
  115. $my_user_is_admin = UserManager::is_admin($uData['user_id']);
  116. if ($my_user_is_admin === false) {
  117. if (is_array($my_url_list) && count($my_url_list) > 0) {
  118. if (in_array($current_access_url_id, $my_url_list)) {
  119. // the user has permission to enter at this site
  120. $_user['user_id'] = $uData['user_id'];
  121. $_user = api_get_user_info($_user['user_id']);
  122. Session::write('_user', $_user);
  123. Event::event_login();
  124. // Redirect to homepage
  125. $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) . 'index.php';
  126. header('Location: '. $sso_target);
  127. exit;
  128. } else {
  129. // user does not have permission for this site
  130. $loginFailed = true;
  131. Session::erase('_uid');
  132. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  133. exit;
  134. }
  135. } else {
  136. // there is no URL in the multiple
  137. // urls list for this user
  138. $loginFailed = true;
  139. Session::erase('_uid');
  140. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  141. exit;
  142. }
  143. } else {
  144. //Only admins of the "main" (first) Chamilo
  145. // portal can login wherever they want
  146. if (in_array(1, $my_url_list)) {
  147. //Check if this admin is admin on the
  148. // principal portal
  149. $_user['user_id'] = $uData['user_id'];
  150. $_user = api_get_user_info($_user['user_id']);
  151. $is_platformAdmin = $uData['status'] == COURSEMANAGER;
  152. Session::write('is_platformAdmin', $is_platformAdmin);
  153. Session::write('_user', $_user);
  154. Event::event_login();
  155. } else {
  156. //Secondary URL admin wants to login
  157. // so we check as a normal user
  158. if (in_array($current_access_url_id, $my_url_list)) {
  159. $_user['user_id'] = $uData['user_id'];
  160. $_user = api_get_user_info($_user['user_id']);
  161. Session::write('_user', $_user);
  162. Event::event_login();
  163. } else {
  164. $loginFailed = true;
  165. Session::erase('_uid');
  166. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  167. exit;
  168. }
  169. }
  170. }
  171. } else {
  172. // user account expired
  173. $loginFailed = true;
  174. Session::erase('_uid');
  175. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_expired');
  176. exit;
  177. }
  178. } else {
  179. //User not active
  180. $loginFailed = true;
  181. Session::erase('_uid');
  182. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_inactive');
  183. exit;
  184. }
  185. } else {
  186. //SHA1 of password is wrong
  187. $loginFailed = true;
  188. Session::erase('_uid');
  189. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_password');
  190. exit;
  191. }
  192. } else {
  193. //Auth_source is wrong
  194. $loginFailed = true;
  195. Session::erase('_uid');
  196. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_authentication_source');
  197. exit;
  198. }
  199. } else {
  200. //No user by that login
  201. $loginFailed = true;
  202. Session::erase('_uid');
  203. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_not_found');
  204. exit;
  205. }
  206. return $loginFailed;
  207. }
  208. /**
  209. * Decode the cookie (this function may vary depending on the
  210. * Single Sign On implementation
  211. * @param string Encoded cookie
  212. * @return array Parsed and unencoded cookie
  213. */
  214. private function decode_cookie($cookie)
  215. {
  216. return unserialize(base64_decode($cookie));
  217. }
  218. /**
  219. * Generate the URL for profile editing for a any user or the current user
  220. * @param int $userId Optional. The user id
  221. * @param boolean $asAdmin Optional. Whether get the URL for the platform admin
  222. * @return string If the URL is obtained return the drupal_user_id. Otherwise return false
  223. */
  224. public function generateProfileEditingURL($userId = 0, $asAdmin = false)
  225. {
  226. $userId = intval($userId);
  227. if (empty($userId)) {
  228. $userId = api_get_user_id();
  229. }
  230. $userExtraFieldValue = new ExtraFieldValue('user');
  231. $drupalUserIdData = $userExtraFieldValue->get_values_by_handler_and_field_variable($userId, 'drupal_user_id');
  232. // If this is an administrator, allow him to make some changes in
  233. // the Chamilo profile
  234. if ($asAdmin && api_is_platform_admin(true)) {
  235. return api_get_path(WEB_CODE_PATH) . "admin/user_edit.php?user_id=$userId";
  236. }
  237. // If the user doesn't match a Drupal user, give the normal profile
  238. // link
  239. if ($drupalUserIdData === false) {
  240. return api_get_path(WEB_CODE_PATH) . 'auth/profile.php';
  241. }
  242. // In all other cases, generate a link to the Drupal profile edition
  243. $drupalUserId = $drupalUserIdData['field_value'];
  244. $url = "{$this->protocol}{$this->domain}/user/{$drupalUserId}/edit";
  245. return $url;
  246. }
  247. }