sso.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 arbitrary external web application (given some light
  7. * development there) and is based on the Drupal-Chamilo module implementation.
  8. * To develop a new authentication mechanism, please extend this class and
  9. * overwrite its method, then modify the corresponding calling code in
  10. * main/inc/local.inc.php
  11. * @package chamilo.auth.sso
  12. */
  13. /**
  14. * The SSO class allows for management or remote Single Sign On resources
  15. */
  16. class sso
  17. {
  18. public $protocol; // 'http://',
  19. public $domain; // 'localhost/project/drupal5',
  20. public $auth_uri; // '/?q=user',
  21. public $deauth_uri; // '/?q=logout',
  22. public $referer; // http://my.chamilo.com/main/auth/profile.php
  23. /*
  24. * referrer_uri: [some/path/inside/Chamilo], might be used by module to
  25. * redirect the user to where he wanted to go initially in Chamilo
  26. */
  27. public $referrer_uri;
  28. /**
  29. * Instanciates the object, initializing all relevant URL strings
  30. */
  31. public function __construct()
  32. {
  33. $this->protocol = api_get_setting('sso_authentication_protocol');
  34. // There can be multiple domains, so make sure to take only the first
  35. // This might be later extended with a decision process
  36. $domains = explode(',', api_get_setting('sso_authentication_domain'));
  37. $this->domain = trim($domains[0]);
  38. $this->auth_uri = api_get_setting('sso_authentication_auth_uri');
  39. $this->deauth_uri = api_get_setting('sso_authentication_unauth_uri');
  40. //cut the string to avoid recursive URL construction in case of failure
  41. $this->referer = $this->protocol.$_SERVER['HTTP_HOST'].substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'sso'));
  42. $this->deauth_url = $this->protocol.$this->domain.$this->deauth_uri;
  43. $this->master_url = $this->protocol.$this->domain.$this->auth_uri;
  44. $this->referrer_uri = base64_encode($_SERVER['REQUEST_URI']);
  45. $this->target = api_get_path(WEB_PATH);
  46. }
  47. /**
  48. * Unlogs the user from the remote server
  49. */
  50. public function logout()
  51. {
  52. header('Location: '.$this->deauth_url);
  53. exit;
  54. }
  55. /**
  56. * Sends the user to the master URL for a check of active connection
  57. */
  58. public function ask_master()
  59. {
  60. $tempKey = api_generate_password(32);
  61. $params = 'sso_referer='.urlencode($this->referer).
  62. '&sso_target='.urlencode($this->target).
  63. '&sso_challenge='.$tempKey.
  64. '&sso_ruri='.urlencode($this->referrer_uri);
  65. Session::write('tempkey', $tempKey);
  66. if (strpos($this->master_url, "?") === false) {
  67. $params = "?$params";
  68. } else {
  69. $params = "&$params";
  70. }
  71. header('Location: '.$this->master_url.$params);
  72. exit;
  73. }
  74. /**
  75. * Validates the received active connection data with the database
  76. * @return bool Return the loginFailed variable value to local.inc.php
  77. */
  78. public function check_user()
  79. {
  80. global $_user;
  81. $loginFailed = false;
  82. //change the way we recover the cookie depending on how it is formed
  83. $sso = $this->decode_cookie($_GET['sso_cookie']);
  84. //error_log('check_user');
  85. //error_log('sso decode cookie: '.print_r($sso,1));
  86. //lookup the user in the main database
  87. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  88. $sql = "SELECT user_id, username, password, auth_source, active, expiration_date, status
  89. FROM $user_table
  90. WHERE username = '".trim(Database::escape_string($sso['username']))."'";
  91. $result = Database::query($sql);
  92. if (Database::num_rows($result) > 0) {
  93. //error_log('user exists');
  94. $uData = Database::fetch_array($result);
  95. //Check the user's password
  96. if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) {
  97. //This user's authentification is managed by Chamilo itself
  98. // check the user's password
  99. // password hash comes already parsed in sha1, md5 or none
  100. /*
  101. error_log($sso['secret']);
  102. error_log($uData['password']);
  103. error_log($sso['username']);
  104. error_log($uData['username']);
  105. */
  106. global $_configuration;
  107. // Two possible authentication methods here: legacy using password
  108. // and new using a temporary, session-fixed, tempkey
  109. if (($sso['username'] == $uData['username']
  110. && $sso['secret'] === sha1(
  111. $uData['username'].
  112. Session::read('tempkey').
  113. $_configuration['security_key']
  114. )
  115. )
  116. or (
  117. ($sso['secret'] === sha1($uData['password']))
  118. && ($sso['username'] == $uData['username'])
  119. )
  120. ) {
  121. //error_log('user n password are ok');
  122. //Check if the account is active (not locked)
  123. if ($uData['active']=='1') {
  124. // check if the expiration date has not been reached
  125. if (empty($uData['expiration_date'])
  126. or $uData['expiration_date'] > date('Y-m-d H:i:s')
  127. or $uData['expiration_date']=='0000-00-00 00:00:00') {
  128. //If Multiple URL is enabled
  129. if (api_get_multiple_access_url()) {
  130. //Check the access_url configuration setting if
  131. // the user is registered in the access_url_rel_user table
  132. //Getting the current access_url_id of the platform
  133. $current_access_url_id = api_get_current_access_url_id();
  134. // my user is subscribed in these
  135. //sites: $my_url_list
  136. $my_url_list = api_get_access_url_from_user($uData['user_id']);
  137. } else {
  138. $current_access_url_id = 1;
  139. $my_url_list = array(1);
  140. }
  141. $my_user_is_admin = UserManager::is_admin($uData['user_id']);
  142. if ($my_user_is_admin === false) {
  143. if (is_array($my_url_list) && count($my_url_list) > 0) {
  144. if (in_array($current_access_url_id, $my_url_list)) {
  145. // the user has permission to enter at this site
  146. $_user['user_id'] = $uData['user_id'];
  147. $_user = api_get_user_info($_user['user_id']);
  148. $_user['uidReset'] = true;
  149. Session::write('_user', $_user);
  150. Event::event_login($_user['user_id']);
  151. // Redirect to homepage
  152. $sso_target = '';
  153. if (!empty($sso['ruri'])) {
  154. //The referrer URI is *only* used if
  155. // the user credentials are OK, which
  156. // should be protection enough
  157. // against evil URL spoofing...
  158. $sso_target = api_get_path(WEB_PATH) . base64_decode($sso['ruri']);
  159. } else {
  160. $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) . 'index.php';
  161. }
  162. header('Location: '. $sso_target);
  163. exit;
  164. } else {
  165. // user does not have permission for this site
  166. $loginFailed = true;
  167. Session::erase('_uid');
  168. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  169. exit;
  170. }
  171. } else {
  172. // there is no URL in the multiple
  173. // urls list for this user
  174. $loginFailed = true;
  175. Session::erase('_uid');
  176. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
  177. exit;
  178. }
  179. } else {
  180. //Only admins of the "main" (first) Chamilo
  181. // portal can login wherever they want
  182. if (in_array(1, $my_url_list)) {
  183. //Check if this admin is admin on the
  184. // principal portal
  185. $_user['user_id'] = $uData['user_id'];
  186. $_user = api_get_user_info($_user['user_id']);
  187. $is_platformAdmin = $uData['status'] == COURSEMANAGER;
  188. Session::write('is_platformAdmin', $is_platformAdmin);
  189. Session::write('_user', $_user);
  190. Event::event_login($_user['user_id']);
  191. } else {
  192. //Secondary URL admin wants to login
  193. // so we check as a normal user
  194. if (in_array($current_access_url_id, $my_url_list)) {
  195. $_user['user_id'] = $uData['user_id'];
  196. $_user = api_get_user_info($_user['user_id']);
  197. Session::write('_user', $_user);
  198. Event::event_login($_user['user_id']);
  199. } else {
  200. $loginFailed = true;
  201. Session::erase('_uid');
  202. header(
  203. 'Location: '.api_get_path(WEB_PATH)
  204. .'index.php?loginFailed=1&error=access_url_inactive'
  205. );
  206. exit;
  207. }
  208. }
  209. }
  210. } else {
  211. // user account expired
  212. $loginFailed = true;
  213. Session::erase('_uid');
  214. header(
  215. 'Location: '.api_get_path(WEB_PATH)
  216. .'index.php?loginFailed=1&error=account_expired'
  217. );
  218. exit;
  219. }
  220. } else {
  221. //User not active
  222. $loginFailed = true;
  223. Session::erase('_uid');
  224. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=account_inactive');
  225. exit;
  226. }
  227. } else {
  228. //SHA1 of password is wrong
  229. $loginFailed = true;
  230. Session::erase('_uid');
  231. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=wrong_password');
  232. exit;
  233. }
  234. } else {
  235. //Auth_source is wrong
  236. $loginFailed = true;
  237. Session::erase('_uid');
  238. header(
  239. 'Location: '.api_get_path(WEB_PATH)
  240. .'index.php?loginFailed=1&error=wrong_authentication_source'
  241. );
  242. exit;
  243. }
  244. } else {
  245. //No user by that login
  246. $loginFailed = true;
  247. Session::erase('_uid');
  248. header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=user_not_found');
  249. exit;
  250. }
  251. return $loginFailed;
  252. }
  253. /**
  254. * Decode the cookie (this function may vary depending on the
  255. * Single Sign On implementation
  256. * @param string Encoded cookie
  257. * @return array Parsed and unencoded cookie
  258. */
  259. private function decode_cookie($cookie)
  260. {
  261. return unserialize(base64_decode($cookie));
  262. }
  263. /**
  264. * Generate the URL for profile editing for a any user or the current user
  265. * @param int $userId Optional. The user id
  266. * @param boolean $asAdmin Optional. Whether get the URL for the platform admin
  267. * @return string The SSO URL
  268. */
  269. public function generateProfileEditingURL($userId = 0, $asAdmin = false)
  270. {
  271. $userId = intval($userId);
  272. if ($asAdmin && api_is_platform_admin(true)) {
  273. return api_get_path(WEB_CODE_PATH) . "admin/user_edit.php?user_id=$userId";
  274. }
  275. return api_get_path(WEB_CODE_PATH) . 'auth/profile.php';
  276. }
  277. }