loginwebpage.class.inc.php 31 KB

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