loginwebpage.class.inc.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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. $oEmail->SetRecipientFrom($sTo);
  221. $oEmail->SetSubject(Dict::S('UI:ResetPwd-EmailSubject'));
  222. $sResetUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?loginop=reset_pwd&auth_user='.urlencode($oUser->Get('login')).'&token='.urlencode($sToken);
  223. $oEmail->SetBody(Dict::Format('UI:ResetPwd-EmailBody', $sResetUrl));
  224. $iRes = $oEmail->Send($aIssues, true /* force synchronous exec */);
  225. switch ($iRes)
  226. {
  227. //case EMAIL_SEND_PENDING:
  228. case EMAIL_SEND_OK:
  229. break;
  230. case EMAIL_SEND_ERROR:
  231. default:
  232. IssueLog::Error('Failed to send the email with the NEW password for '.$oUser->Get('friendlyname').': '.implode(', ', $aIssues));
  233. throw new Exception(Dict::S('UI:ResetPwd-Error-Send'));
  234. }
  235. $this->DisplayLoginHeader();
  236. $this->add("<div id=\"login\">\n");
  237. $this->add("<h1>".Dict::S('UI:Login:ForgotPwdForm')."</h1>\n");
  238. $this->add("<p>".Dict::S('UI:ResetPwd-EmailSent')."</p>");
  239. $this->add("<form method=\"post\">\n");
  240. $this->add("<table>\n");
  241. $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");
  242. $this->add("</table>\n");
  243. $this->add("</form>\n");
  244. $this->add("</div\n");
  245. }
  246. catch(Exception $e)
  247. {
  248. $this->DisplayForgotPwdForm(true, $e->getMessage());
  249. }
  250. }
  251. public function DisplayResetPwdForm()
  252. {
  253. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  254. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  255. UserRights::Login($sAuthUser); // Set the user's language
  256. $oUser = UserRights::GetUserObject();
  257. $this->DisplayLoginHeader();
  258. $this->add("<div id=\"login\">\n");
  259. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  260. if ($oUser == null)
  261. {
  262. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  263. }
  264. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  265. {
  266. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  267. }
  268. else
  269. {
  270. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-EnterPassword', $oUser->GetFriendlyName())."</p>\n");
  271. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  272. $this->add_script(
  273. <<<EOF
  274. function DoCheckPwd()
  275. {
  276. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  277. {
  278. alert('$sInconsistenPwdMsg');
  279. return false;
  280. }
  281. return true;
  282. }
  283. EOF
  284. );
  285. $this->add("<form method=\"post\">\n");
  286. $this->add("<table>\n");
  287. $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");
  288. $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");
  289. $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");
  290. $this->add("</table>\n");
  291. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_reset_pwd\" />\n");
  292. $this->add("<input type=\"hidden\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" />\n");
  293. $this->add("<input type=\"hidden\" name=\"token\" value=\"".htmlentities($sToken, ENT_QUOTES, 'UTF-8')."\" />\n");
  294. $this->add("</form>\n");
  295. $this->add("</div\n");
  296. }
  297. }
  298. public function DoResetPassword()
  299. {
  300. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  301. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  302. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  303. UserRights::Login($sAuthUser); // Set the user's language
  304. $oUser = UserRights::GetUserObject();
  305. $this->DisplayLoginHeader();
  306. $this->add("<div id=\"login\">\n");
  307. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  308. if ($oUser == null)
  309. {
  310. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  311. }
  312. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  313. {
  314. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  315. }
  316. else
  317. {
  318. // Trash the token and change the password
  319. $oUser->Set('reset_pwd_token', '');
  320. $oUser->SetPassword($sNewPwd); // Does record the change into the DB
  321. $this->add("<p>".Dict::S('UI:ResetPwd-Ready')."</p>");
  322. $sUrl = utils::GetAbsoluteUrlAppRoot();
  323. $this->add("<p><a href=\"$sUrl\">".Dict::S('UI:ResetPwd-Login')."</a></p>");
  324. }
  325. $this->add("</div\n");
  326. }
  327. public function DisplayChangePwdForm($bFailedLogin = false)
  328. {
  329. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  330. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  331. $this->add_script(<<<EOF
  332. function GoBack()
  333. {
  334. window.history.back();
  335. }
  336. function DoCheckPwd()
  337. {
  338. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  339. {
  340. alert('$sInconsistenPwdMsg');
  341. return false;
  342. }
  343. return true;
  344. }
  345. EOF
  346. );
  347. $this->DisplayLoginHeader();
  348. $this->add("<div id=\"login\">\n");
  349. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  350. if ($bFailedLogin)
  351. {
  352. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  353. }
  354. $this->add("<form method=\"post\">\n");
  355. $this->add("<table>\n");
  356. $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");
  357. $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");
  358. $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");
  359. $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");
  360. $this->add("</table>\n");
  361. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  362. $this->add("</form>\n");
  363. $this->add("</div>\n");
  364. }
  365. static function ResetSession()
  366. {
  367. if (isset($_SESSION['login_mode']))
  368. {
  369. $sPreviousLoginMode = $_SESSION['login_mode'];
  370. }
  371. else
  372. {
  373. $sPreviousLoginMode = '';
  374. }
  375. // Unset all of the session variables.
  376. unset($_SESSION['auth_user']);
  377. unset($_SESSION['login_mode']);
  378. // If it's desired to kill the session, also delete the session cookie.
  379. // Note: This will destroy the session, and not just the session data!
  380. }
  381. static function SecureConnectionRequired()
  382. {
  383. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  384. }
  385. /**
  386. * Guess if a string looks like an UTF-8 string based on some ranges of multi-bytes encoding
  387. * @param string $sString
  388. * @return bool True if the string contains some typical UTF-8 multi-byte sequences
  389. */
  390. static function LooksLikeUTF8($sString)
  391. {
  392. return preg_match('%(?:
  393. [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  394. |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  395. |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  396. |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  397. |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  398. |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  399. |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  400. )+%xs', $sString);
  401. }
  402. /**
  403. * Attempt a login
  404. *
  405. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  406. */
  407. protected static function Login($iOnExit)
  408. {
  409. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  410. {
  411. // Non secured URL... request for a secure connection
  412. throw new Exception('Secure connection required!');
  413. }
  414. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  415. if (isset($_SESSION['auth_user']))
  416. {
  417. //echo "User: ".$_SESSION['auth_user']."\n";
  418. // Already authentified
  419. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  420. return true;
  421. }
  422. else
  423. {
  424. $index = 0;
  425. $sLoginMode = '';
  426. $sAuthentication = 'internal';
  427. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  428. {
  429. $sLoginType = $aAllowedLoginTypes[$index];
  430. switch($sLoginType)
  431. {
  432. case 'cas':
  433. utils::InitCASClient();
  434. // check CAS authentication
  435. if (phpCAS::isAuthenticated())
  436. {
  437. $sAuthUser = phpCAS::getUser();
  438. $sAuthPwd = '';
  439. $sLoginMode = 'cas';
  440. $sAuthentication = 'external';
  441. }
  442. break;
  443. case 'form':
  444. // iTop standard mode: form based authentication
  445. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  446. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', false, 'raw_data');
  447. if ($sAuthUser != '')
  448. {
  449. $sLoginMode = 'form';
  450. }
  451. break;
  452. case 'basic':
  453. // Standard PHP authentication method, works with Apache...
  454. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  455. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  456. {
  457. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  458. $sLoginMode = 'basic';
  459. }
  460. else if (isset($_SERVER['PHP_AUTH_USER']))
  461. {
  462. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  463. // Unfortunately, the RFC is not clear about the encoding...
  464. // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
  465. // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
  466. if (!self::LooksLikeUTF8($sAuthUser))
  467. {
  468. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  469. // Supposed to be harmless in case of a plain ASCII string...
  470. $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
  471. }
  472. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  473. if (!self::LooksLikeUTF8($sAuthPwd))
  474. {
  475. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  476. // Supposed to be harmless in case of a plain ASCII string...
  477. $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
  478. }
  479. $sLoginMode = 'basic';
  480. }
  481. break;
  482. case 'external':
  483. // Web server supplied authentication
  484. $bExternalAuth = false;
  485. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  486. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  487. if ($sAuthUser && (strlen($sAuthUser) > 0))
  488. {
  489. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  490. $sLoginMode = 'external';
  491. $sAuthentication = 'external';
  492. }
  493. break;
  494. case 'url':
  495. // Credentials passed directly in the url
  496. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  497. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  498. if (($sAuthUser != '') && ($sAuthPwd != null))
  499. {
  500. $sLoginMode = 'url';
  501. }
  502. break;
  503. }
  504. $index++;
  505. }
  506. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  507. if ($sLoginMode == '')
  508. {
  509. // First connection
  510. $sDesiredLoginMode = utils::ReadParam('login_mode');
  511. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  512. {
  513. $sLoginMode = $sDesiredLoginMode;
  514. }
  515. else
  516. {
  517. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  518. }
  519. if (($iOnExit == self::EXIT_HTTP_401) || ($sLoginMode == 'basic'))
  520. {
  521. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  522. header('HTTP/1.0 401 Unauthorized');
  523. header('Content-type: text/html; charset=iso-8859-1');
  524. exit;
  525. }
  526. else if($iOnExit == self::EXIT_RETURN_FALSE)
  527. {
  528. return false;
  529. }
  530. else
  531. {
  532. $oPage = self::NewLoginWebPage();
  533. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  534. $oPage->output();
  535. exit;
  536. }
  537. }
  538. else
  539. {
  540. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  541. {
  542. //echo "Check Credentials returned false for user $sAuthUser!";
  543. self::ResetSession();
  544. if (($iOnExit == self::EXIT_HTTP_401))
  545. {
  546. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  547. header('HTTP/1.0 401 Unauthorized');
  548. header('Content-type: text/html; charset=iso-8859-1');
  549. exit;
  550. }
  551. else if($iOnExit == self::EXIT_RETURN_FALSE)
  552. {
  553. return false;
  554. }
  555. else
  556. {
  557. $oPage = self::NewLoginWebPage();
  558. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  559. $oPage->output();
  560. exit;
  561. }
  562. }
  563. else
  564. {
  565. // User is Ok, let's save it in the session and proceed with normal login
  566. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  567. if (MetaModel::GetConfig()->Get('log_usage'))
  568. {
  569. $oLog = new EventLoginUsage();
  570. $oLog->Set('userinfo', UserRights::GetUser());
  571. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  572. $oLog->Set('message', 'Successful login');
  573. $oLog->DBInsertNoReload();
  574. }
  575. $_SESSION['auth_user'] = $sAuthUser;
  576. $_SESSION['login_mode'] = $sLoginMode;
  577. }
  578. }
  579. }
  580. return true;
  581. }
  582. /**
  583. * Overridable: depending on the user, head toward a dedicated portal
  584. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  585. */
  586. protected static function ChangeLocation($bIsAllowedToPortalUsers)
  587. {
  588. if ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  589. {
  590. // No rights to be here, redirect to the portal
  591. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  592. }
  593. }
  594. /**
  595. * Check if the user is already authentified, if yes, then performs some additional validations:
  596. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  597. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  598. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  599. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  600. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  601. */
  602. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT)
  603. {
  604. $sMessage = ''; // In case we need to return a message to the calling web page
  605. $operation = utils::ReadParam('loginop', '');
  606. if ($operation == 'logoff')
  607. {
  608. if (isset($_SESSION['login_mode']))
  609. {
  610. $sLoginMode = $_SESSION['login_mode'];
  611. }
  612. else
  613. {
  614. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  615. if (count($aAllowedLoginTypes) > 0)
  616. {
  617. $sLoginMode = $aAllowedLoginTypes[0];
  618. }
  619. else
  620. {
  621. $sLoginMode = 'form';
  622. }
  623. }
  624. self::ResetSession();
  625. $oPage = self::NewLoginWebPage();
  626. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  627. $oPage->output();
  628. exit;
  629. }
  630. else if ($operation == 'forgot_pwd')
  631. {
  632. $oPage = self::NewLoginWebPage();
  633. $oPage->DisplayForgotPwdForm();
  634. $oPage->output();
  635. exit;
  636. }
  637. else if ($operation == 'forgot_pwd_go')
  638. {
  639. $oPage = self::NewLoginWebPage();
  640. $oPage->ForgotPwdGo();
  641. $oPage->output();
  642. exit;
  643. }
  644. else if ($operation == 'reset_pwd')
  645. {
  646. $oPage = self::NewLoginWebPage();
  647. $oPage->DisplayResetPwdForm();
  648. $oPage->output();
  649. exit;
  650. }
  651. else if ($operation == 'do_reset_pwd')
  652. {
  653. $oPage = self::NewLoginWebPage();
  654. $oPage->DoResetPassword();
  655. $oPage->output();
  656. exit;
  657. }
  658. else if ($operation == 'change_pwd')
  659. {
  660. $sAuthUser = $_SESSION['auth_user'];
  661. UserRights::Login($sAuthUser); // Set the user's language
  662. $oPage = self::NewLoginWebPage();
  663. $oPage->DisplayChangePwdForm();
  664. $oPage->output();
  665. exit;
  666. }
  667. if ($operation == 'do_change_pwd')
  668. {
  669. $sAuthUser = $_SESSION['auth_user'];
  670. UserRights::Login($sAuthUser); // Set the user's language
  671. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  672. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  673. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  674. {
  675. $oPage = self::NewLoginWebPage();
  676. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  677. $oPage->output();
  678. exit;
  679. }
  680. $sMessage = Dict::S('UI:Login:PasswordChanged');
  681. }
  682. $bRet = self::Login($iOnExit);
  683. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  684. {
  685. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  686. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  687. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  688. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  689. $oP->output();
  690. exit;
  691. }
  692. call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $bIsAllowedToPortalUsers);
  693. if ($iOnExit == self::EXIT_RETURN_FALSE)
  694. {
  695. return $bRet;
  696. }
  697. else
  698. {
  699. return $sMessage;
  700. }
  701. }
  702. } // End of class