loginwebpage.class.inc.php 27 KB

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