sso.class.php 14 KB

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