loginwebpage.class.inc.php 27 KB

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