loginwebpage.class.inc.php 30 KB

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