loginwebpage.class.inc.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class LoginWebPage
  20. *
  21. * @copyright Copyright (C) 2010-2013 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once(APPROOT."/application/nicewebpage.class.inc.php");
  25. /**
  26. * Web page used for displaying the login form
  27. */
  28. class LoginWebPage extends NiceWebPage
  29. {
  30. const EXIT_PROMPT = 0;
  31. const EXIT_HTTP_401 = 1;
  32. protected static $sHandlerClass = __class__;
  33. public static function RegisterHandler($sClass)
  34. {
  35. self::$sHandlerClass = $sClass;
  36. }
  37. public static function NewLoginWebPage()
  38. {
  39. return new self::$sHandlerClass;
  40. }
  41. protected static $m_sLoginFailedMessage = '';
  42. public function __construct($sTitle = 'iTop Login')
  43. {
  44. parent::__construct($sTitle);
  45. $this->SetStyleSheet();
  46. $this->add_header("Cache-control: no-cache");
  47. }
  48. public function SetStyleSheet()
  49. {
  50. $this->add_linked_stylesheet("../css/login.css");
  51. }
  52. public static function SetLoginFailedMessage($sMessage)
  53. {
  54. self::$m_sLoginFailedMessage = $sMessage;
  55. }
  56. public function EnableResetPassword()
  57. {
  58. return MetaModel::GetConfig()->Get('forgot_password');
  59. }
  60. public function DisplayLoginHeader($bMainAppLogo = false)
  61. {
  62. if ($bMainAppLogo)
  63. {
  64. $sLogo = 'itop-logo.png';
  65. $sBrandingLogo = 'main-logo.png';
  66. }
  67. else
  68. {
  69. $sLogo = 'itop-logo-external.png';
  70. $sBrandingLogo = 'login-logo.png';
  71. }
  72. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  73. $sIconUrl = Utils::GetConfig()->Get('app_icon_url');
  74. $sDisplayIcon = utils::GetAbsoluteUrlAppRoot().'images/'.$sLogo;
  75. if (file_exists(MODULESROOT.'branding/'.$sBrandingLogo))
  76. {
  77. $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot().'branding/'.$sBrandingLogo;
  78. }
  79. $this->add("<div id=\"login-logo\"><a href=\"".htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8')."\"><img title=\"$sVersionShort\" src=\"$sDisplayIcon\"></a></div>\n");
  80. }
  81. public function DisplayLoginForm($sLoginType, $bFailedLogin = false)
  82. {
  83. switch($sLoginType)
  84. {
  85. case 'cas':
  86. utils::InitCASClient();
  87. // force CAS authentication
  88. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  89. break;
  90. case 'basic':
  91. case 'url':
  92. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  93. $this->add_header('HTTP/1.0 401 Unauthorized');
  94. $this->add_header('Content-type: text/html; charset=iso-8859-1');
  95. // Note: displayed when the user will click on Cancel
  96. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  97. break;
  98. case 'external':
  99. case 'form':
  100. default: // In case the settings get messed up...
  101. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  102. $sAuthPwd = utils::ReadParam('suggest_pwd', '', true, 'raw_data');
  103. $this->DisplayLoginHeader();
  104. $this->add("<div id=\"login\">\n");
  105. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  106. if ($bFailedLogin)
  107. {
  108. if (self::$m_sLoginFailedMessage != '')
  109. {
  110. $this->add("<p class=\"hilite\">".self::$m_sLoginFailedMessage."</p>\n");
  111. }
  112. else
  113. {
  114. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  115. }
  116. }
  117. else
  118. {
  119. $this->add("<p>".Dict::S('UI:Login:IdentifyYourself')."</p>\n");
  120. }
  121. $this->add("<form method=\"post\">\n");
  122. $this->add("<table>\n");
  123. $sForgotPwd = $this->EnableResetPassword() ? $this->ForgotPwdLink() : '';
  124. $this->add("<tr><td style=\"text-align:right\"><label for=\"user\">".Dict::S('UI:Login:UserNamePrompt').":</label></td><td style=\"text-align:left\"><input id=\"user\" type=\"text\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" /></td></tr>\n");
  125. $this->add("<tr><td style=\"text-align:right\"><label for=\"pwd\">".Dict::S('UI:Login:PasswordPrompt').":</label></td><td style=\"text-align:left\"><input id=\"pwd\" type=\"password\" name=\"auth_pwd\" value=\"".htmlentities($sAuthPwd, ENT_QUOTES, 'UTF-8')."\" /></td></tr>\n");
  126. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"><span class=\"btn_border\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Login')."\" /></span></td></tr>\n");
  127. if (strlen($sForgotPwd) > 0)
  128. {
  129. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\">$sForgotPwd</td></tr>\n");
  130. }
  131. $this->add("</table>\n");
  132. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  133. // Keep the OTHER parameters posted
  134. foreach($_POST as $sPostedKey => $postedValue)
  135. {
  136. if (!in_array($sPostedKey, array('auth_user', 'auth_pwd')))
  137. {
  138. if (is_array($postedValue))
  139. {
  140. foreach($postedValue as $sKey => $sValue)
  141. {
  142. $this->add("<input type=\"hidden\" name=\"".htmlentities($sPostedKey, ENT_QUOTES, 'UTF-8')."[".htmlentities($sKey, ENT_QUOTES, 'UTF-8')."]\" value=\"".htmlentities($sValue, ENT_QUOTES, 'UTF-8')."\" />\n");
  143. }
  144. }
  145. else
  146. {
  147. $this->add("<input type=\"hidden\" name=\"".htmlentities($sPostedKey, ENT_QUOTES, 'UTF-8')."\" value=\"".htmlentities($postedValue, ENT_QUOTES, 'UTF-8')."\" />\n");
  148. }
  149. }
  150. }
  151. $this->add("</form>\n");
  152. $this->add(Dict::S('UI:Login:About'));
  153. $this->add("</div>\n");
  154. break;
  155. }
  156. }
  157. /**
  158. * Return '' to disable this feature
  159. */
  160. public function ForgotPwdLink()
  161. {
  162. $sUrl = '?loginop=forgot_pwd';
  163. $sHtml = "<a href=\"$sUrl\" target=\"_blank\">".Dict::S('UI:Login:ForgotPwd')."</a>";
  164. return $sHtml;
  165. }
  166. public function DisplayForgotPwdForm($bFailedToReset = false, $sFailureReason = null)
  167. {
  168. $this->DisplayLoginHeader();
  169. $this->add("<div id=\"login\">\n");
  170. $this->add("<h1>".Dict::S('UI:Login:ForgotPwdForm')."</h1>\n");
  171. $this->add("<p>".Dict::S('UI:Login:ForgotPwdForm+')."</p>\n");
  172. if ($bFailedToReset)
  173. {
  174. $this->add("<p class=\"hilite\">".Dict::Format('UI:Login:ResetPwdFailed', $sFailureReason)."</p>\n");
  175. }
  176. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  177. $this->add("<form method=\"post\">\n");
  178. $this->add("<table>\n");
  179. $this->add("<tr><td colspan=\"2\" class=\"center\"><label for=\"user\">".Dict::S('UI:Login:UserNamePrompt').":</label><input id=\"user\" type=\"text\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" /></td></tr>\n");
  180. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"><span class=\"btn_border\"><input type=\"button\" onClick=\"window.close();\" value=\"".Dict::S('UI:Button:Cancel')."\" /></span>&nbsp;&nbsp;<span class=\"btn_border\"><input type=\"submit\" value=\"".Dict::S('UI:Login:ResetPassword')."\" /></span></td></tr>\n");
  181. $this->add("</table>\n");
  182. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"forgot_pwd_go\" />\n");
  183. $this->add("</form>\n");
  184. $this->add("</div>\n");
  185. }
  186. protected function ForgotPwdGo()
  187. {
  188. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  189. try
  190. {
  191. UserRights::Login($sAuthUser); // Set the user's language (if possible!)
  192. $oUser = UserRights::GetUserObject();
  193. if ($oUser == null)
  194. {
  195. throw new Exception(Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser));
  196. }
  197. if (!MetaModel::IsValidAttCode(get_class($oUser), 'reset_pwd_token'))
  198. {
  199. throw new Exception(Dict::S('UI:ResetPwd-Error-NotPossible'));
  200. }
  201. if (!$oUser->CanChangePassword())
  202. {
  203. throw new Exception(Dict::S('UI:ResetPwd-Error-FixedPwd'));
  204. }
  205. $sTo = $oUser->GetResetPasswordEmail(); // throws Exceptions if not allowed
  206. if ($sTo == '')
  207. {
  208. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmail'));
  209. }
  210. // This token allows the user to change the password without knowing the previous one
  211. $sToken = substr(md5(APPROOT.uniqid()), 0, 16);
  212. $oUser->Set('reset_pwd_token', $sToken);
  213. CMDBObject::SetTrackInfo('Reset password');
  214. $oUser->DBUpdate();
  215. $oEmail = new Email();
  216. $oEmail->SetRecipientTO($sTo);
  217. $oEmail->SetRecipientFrom($sTo);
  218. $oEmail->SetSubject(Dict::S('UI:ResetPwd-EmailSubject'));
  219. $sResetUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?loginop=reset_pwd&auth_user='.urlencode($oUser->Get('login')).'&token='.urlencode($sToken);
  220. $oEmail->SetBody(Dict::Format('UI:ResetPwd-EmailBody', $sResetUrl));
  221. $iRes = $oEmail->Send($aIssues, true /* force synchronous exec */);
  222. switch ($iRes)
  223. {
  224. //case EMAIL_SEND_PENDING:
  225. case EMAIL_SEND_OK:
  226. break;
  227. case EMAIL_SEND_ERROR:
  228. default:
  229. IssueLog::Error('Failed to send the email with the NEW password for '.$oUser->Get('friendlyname').': '.implode(', ', $aIssues));
  230. throw new Exception(Dict::S('UI:ResetPwd-Error-Send'));
  231. }
  232. $this->DisplayLoginHeader();
  233. $this->add("<div id=\"login\">\n");
  234. $this->add("<h1>".Dict::S('UI:Login:ForgotPwdForm')."</h1>\n");
  235. $this->add("<p>".Dict::S('UI:ResetPwd-EmailSent')."</p>");
  236. $this->add("<form method=\"post\">\n");
  237. $this->add("<table>\n");
  238. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"><input type=\"button\" onClick=\"window.close();\" value=\"".Dict::S('UI:Button:Done')."\" /></td></tr>\n");
  239. $this->add("</table>\n");
  240. $this->add("</form>\n");
  241. $this->add("</div\n");
  242. }
  243. catch(Exception $e)
  244. {
  245. $this->DisplayForgotPwdForm(true, $e->getMessage());
  246. }
  247. }
  248. public function DisplayResetPwdForm()
  249. {
  250. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  251. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  252. UserRights::Login($sAuthUser); // Set the user's language
  253. $oUser = UserRights::GetUserObject();
  254. $this->DisplayLoginHeader();
  255. $this->add("<div id=\"login\">\n");
  256. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  257. if ($oUser == null)
  258. {
  259. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  260. }
  261. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  262. {
  263. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  264. }
  265. else
  266. {
  267. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-EnterPassword', $oUser->GetFriendlyName())."</p>\n");
  268. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  269. $this->add_script(
  270. <<<EOF
  271. function DoCheckPwd()
  272. {
  273. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  274. {
  275. alert('$sInconsistenPwdMsg');
  276. return false;
  277. }
  278. return true;
  279. }
  280. EOF
  281. );
  282. $this->add("<form method=\"post\">\n");
  283. $this->add("<table>\n");
  284. $this->add("<tr><td style=\"text-align:right\"><label for=\"new_pwd\">".Dict::S('UI:Login:NewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"new_pwd\" name=\"new_pwd\" value=\"\" /></td></tr>\n");
  285. $this->add("<tr><td style=\"text-align:right\"><label for=\"retype_new_pwd\">".Dict::S('UI:Login:RetypeNewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"retype_new_pwd\" name=\"retype_new_pwd\" value=\"\" /></td></tr>\n");
  286. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"><span class=\"btn_border\"><input type=\"submit\" onClick=\"return DoCheckPwd();\" value=\"".Dict::S('UI:Button:ChangePassword')."\" /></span></td></tr>\n");
  287. $this->add("</table>\n");
  288. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_reset_pwd\" />\n");
  289. $this->add("<input type=\"hidden\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" />\n");
  290. $this->add("<input type=\"hidden\" name=\"token\" value=\"".htmlentities($sToken, ENT_QUOTES, 'UTF-8')."\" />\n");
  291. $this->add("</form>\n");
  292. $this->add("</div\n");
  293. }
  294. }
  295. public function DoResetPassword()
  296. {
  297. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  298. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  299. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  300. UserRights::Login($sAuthUser); // Set the user's language
  301. $oUser = UserRights::GetUserObject();
  302. $this->DisplayLoginHeader();
  303. $this->add("<div id=\"login\">\n");
  304. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  305. if ($oUser == null)
  306. {
  307. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  308. }
  309. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  310. {
  311. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  312. }
  313. else
  314. {
  315. // Trash the token and change the password
  316. $oUser->Set('reset_pwd_token', '');
  317. $oUser->SetPassword($sNewPwd); // Does record the change into the DB
  318. $this->add("<p>".Dict::S('UI:ResetPwd-Ready')."</p>");
  319. $sUrl = utils::GetAbsoluteUrlAppRoot();
  320. $this->add("<p><a href=\"$sUrl\">".Dict::S('UI:ResetPwd-Login')."</a></p>");
  321. }
  322. $this->add("</div\n");
  323. }
  324. public function DisplayChangePwdForm($bFailedLogin = false)
  325. {
  326. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  327. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  328. $this->add_script(<<<EOF
  329. function GoBack()
  330. {
  331. window.history.back();
  332. }
  333. function DoCheckPwd()
  334. {
  335. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  336. {
  337. alert('$sInconsistenPwdMsg');
  338. return false;
  339. }
  340. return true;
  341. }
  342. EOF
  343. );
  344. $this->DisplayLoginHeader();
  345. $this->add("<div id=\"login\">\n");
  346. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  347. if ($bFailedLogin)
  348. {
  349. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  350. }
  351. $this->add("<form method=\"post\">\n");
  352. $this->add("<table>\n");
  353. $this->add("<tr><td style=\"text-align:right\"><label for=\"old_pwd\">".Dict::S('UI:Login:OldPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"old_pwd\" name=\"old_pwd\" value=\"\" /></td></tr>\n");
  354. $this->add("<tr><td style=\"text-align:right\"><label for=\"new_pwd\">".Dict::S('UI:Login:NewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"new_pwd\" name=\"new_pwd\" value=\"\" /></td></tr>\n");
  355. $this->add("<tr><td style=\"text-align:right\"><label for=\"retype_new_pwd\">".Dict::S('UI:Login:RetypeNewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"retype_new_pwd\" name=\"retype_new_pwd\" value=\"\" /></td></tr>\n");
  356. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"><span class=\"btn_border\"><input type=\"button\" onClick=\"GoBack();\" value=\"".Dict::S('UI:Button:Cancel')."\" /></span>&nbsp;&nbsp;<span class=\"btn_border\"><input type=\"submit\" onClick=\"return DoCheckPwd();\" value=\"".Dict::S('UI:Button:ChangePassword')."\" /></span></td></tr>\n");
  357. $this->add("</table>\n");
  358. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  359. $this->add("</form>\n");
  360. $this->add("</div>\n");
  361. }
  362. static function ResetSession()
  363. {
  364. if (isset($_SESSION['login_mode']))
  365. {
  366. $sPreviousLoginMode = $_SESSION['login_mode'];
  367. }
  368. else
  369. {
  370. $sPreviousLoginMode = '';
  371. }
  372. // Unset all of the session variables.
  373. unset($_SESSION['auth_user']);
  374. unset($_SESSION['login_mode']);
  375. // If it's desired to kill the session, also delete the session cookie.
  376. // Note: This will destroy the session, and not just the session data!
  377. }
  378. static function SecureConnectionRequired()
  379. {
  380. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  381. }
  382. /**
  383. * Guess if a string looks like an UTF-8 string based on some ranges of multi-bytes encoding
  384. * @param string $sString
  385. * @return bool True if the string contains some typical UTF-8 multi-byte sequences
  386. */
  387. static function LooksLikeUTF8($sString)
  388. {
  389. return preg_match('%(?:
  390. [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  391. |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  392. |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  393. |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  394. |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  395. |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  396. |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  397. )+%xs', $sString);
  398. }
  399. /**
  400. * Attempt a login
  401. *
  402. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  403. */
  404. protected static function Login($iOnExit)
  405. {
  406. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  407. {
  408. // Non secured URL... request for a secure connection
  409. throw new Exception('Secure connection required!');
  410. }
  411. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  412. if (isset($_SESSION['auth_user']))
  413. {
  414. //echo "User: ".$_SESSION['auth_user']."\n";
  415. // Already authentified
  416. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  417. return true;
  418. }
  419. else
  420. {
  421. $index = 0;
  422. $sLoginMode = '';
  423. $sAuthentication = 'internal';
  424. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  425. {
  426. $sLoginType = $aAllowedLoginTypes[$index];
  427. switch($sLoginType)
  428. {
  429. case 'cas':
  430. utils::InitCASClient();
  431. // check CAS authentication
  432. if (phpCAS::isAuthenticated())
  433. {
  434. $sAuthUser = phpCAS::getUser();
  435. $sAuthPwd = '';
  436. $sLoginMode = 'cas';
  437. $sAuthentication = 'external';
  438. }
  439. break;
  440. case 'form':
  441. // iTop standard mode: form based authentication
  442. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  443. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', false, 'raw_data');
  444. if ($sAuthUser != '')
  445. {
  446. $sLoginMode = 'form';
  447. }
  448. break;
  449. case 'basic':
  450. // Standard PHP authentication method, works with Apache...
  451. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  452. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  453. {
  454. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  455. $sLoginMode = 'basic';
  456. }
  457. else if (isset($_SERVER['PHP_AUTH_USER']))
  458. {
  459. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  460. // Unfortunately, the RFC is not clear about the encoding...
  461. // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
  462. // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
  463. if (!self::LooksLikeUTF8($sAuthUser))
  464. {
  465. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  466. // Supposed to be harmless in case of a plain ASCII string...
  467. $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
  468. }
  469. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  470. if (!self::LooksLikeUTF8($sAuthPwd))
  471. {
  472. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  473. // Supposed to be harmless in case of a plain ASCII string...
  474. $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
  475. }
  476. $sLoginMode = 'basic';
  477. }
  478. break;
  479. case 'external':
  480. // Web server supplied authentication
  481. $bExternalAuth = false;
  482. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  483. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  484. if ($sAuthUser && (strlen($sAuthUser) > 0))
  485. {
  486. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  487. $sLoginMode = 'external';
  488. $sAuthentication = 'external';
  489. }
  490. break;
  491. case 'url':
  492. // Credentials passed directly in the url
  493. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  494. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  495. if (($sAuthUser != '') && ($sAuthPwd != null))
  496. {
  497. $sLoginMode = 'url';
  498. }
  499. break;
  500. }
  501. $index++;
  502. }
  503. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  504. if ($sLoginMode == '')
  505. {
  506. // First connection
  507. $sDesiredLoginMode = utils::ReadParam('login_mode');
  508. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  509. {
  510. $sLoginMode = $sDesiredLoginMode;
  511. }
  512. else
  513. {
  514. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  515. }
  516. if ($iOnExit == self::EXIT_HTTP_401)
  517. {
  518. header("HTTP/1.0 401 Unauthorized");
  519. exit;
  520. }
  521. else
  522. {
  523. $oPage = self::NewLoginWebPage();
  524. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  525. $oPage->output();
  526. exit;
  527. }
  528. }
  529. else
  530. {
  531. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  532. {
  533. //echo "Check Credentials returned false for user $sAuthUser!";
  534. self::ResetSession();
  535. if ($iOnExit == self::EXIT_HTTP_401)
  536. {
  537. header("HTTP/1.0 401 Unauthorized");
  538. exit;
  539. }
  540. else
  541. {
  542. $oPage = self::NewLoginWebPage();
  543. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  544. $oPage->output();
  545. exit;
  546. }
  547. }
  548. else
  549. {
  550. // User is Ok, let's save it in the session and proceed with normal login
  551. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  552. if (MetaModel::GetConfig()->Get('log_usage'))
  553. {
  554. $oLog = new EventLoginUsage();
  555. $oLog->Set('userinfo', UserRights::GetUser());
  556. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  557. $oLog->Set('message', 'Successful login');
  558. $oLog->DBInsertNoReload();
  559. }
  560. $_SESSION['auth_user'] = $sAuthUser;
  561. $_SESSION['login_mode'] = $sLoginMode;
  562. }
  563. }
  564. }
  565. }
  566. /**
  567. * Overridable: depending on the user, head toward a dedicated portal
  568. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  569. */
  570. protected static function ChangeLocation($bIsAllowedToPortalUsers)
  571. {
  572. if ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  573. {
  574. // No rights to be here, redirect to the portal
  575. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  576. }
  577. }
  578. /**
  579. * Check if the user is already authentified, if yes, then performs some additional validations:
  580. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  581. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  582. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  583. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  584. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  585. */
  586. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT)
  587. {
  588. $sMessage = ''; // In case we need to return a message to the calling web page
  589. $operation = utils::ReadParam('loginop', '');
  590. if ($operation == 'logoff')
  591. {
  592. if (isset($_SESSION['login_mode']))
  593. {
  594. $sLoginMode = $_SESSION['login_mode'];
  595. }
  596. else
  597. {
  598. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  599. if (count($aAllowedLoginTypes) > 0)
  600. {
  601. $sLoginMode = $aAllowedLoginTypes[0];
  602. }
  603. else
  604. {
  605. $sLoginMode = 'form';
  606. }
  607. }
  608. self::ResetSession();
  609. $oPage = self::NewLoginWebPage();
  610. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  611. $oPage->output();
  612. exit;
  613. }
  614. else if ($operation == 'forgot_pwd')
  615. {
  616. $oPage = self::NewLoginWebPage();
  617. $oPage->DisplayForgotPwdForm();
  618. $oPage->output();
  619. exit;
  620. }
  621. else if ($operation == 'forgot_pwd_go')
  622. {
  623. $oPage = self::NewLoginWebPage();
  624. $oPage->ForgotPwdGo();
  625. $oPage->output();
  626. exit;
  627. }
  628. else if ($operation == 'reset_pwd')
  629. {
  630. $oPage = self::NewLoginWebPage();
  631. $oPage->DisplayResetPwdForm();
  632. $oPage->output();
  633. exit;
  634. }
  635. else if ($operation == 'do_reset_pwd')
  636. {
  637. $oPage = self::NewLoginWebPage();
  638. $oPage->DoResetPassword();
  639. $oPage->output();
  640. exit;
  641. }
  642. else if ($operation == 'change_pwd')
  643. {
  644. $sAuthUser = $_SESSION['auth_user'];
  645. UserRights::Login($sAuthUser); // Set the user's language
  646. $oPage = self::NewLoginWebPage();
  647. $oPage->DisplayChangePwdForm();
  648. $oPage->output();
  649. exit;
  650. }
  651. if ($operation == 'do_change_pwd')
  652. {
  653. $sAuthUser = $_SESSION['auth_user'];
  654. UserRights::Login($sAuthUser); // Set the user's language
  655. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  656. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  657. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  658. {
  659. $oPage = self::NewLoginWebPage();
  660. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  661. $oPage->output();
  662. exit;
  663. }
  664. $sMessage = Dict::S('UI:Login:PasswordChanged');
  665. }
  666. self::Login($iOnExit);
  667. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  668. {
  669. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  670. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  671. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  672. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  673. $oP->output();
  674. exit;
  675. }
  676. call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $bIsAllowedToPortalUsers);
  677. return $sMessage;
  678. }
  679. } // End of class