sso.class.php 14 KB

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