sso.Drupal.class.php 14 KB

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