loginwebpage.class.inc.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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. UserRights::_ResetSessionCache();
  391. // If it's desired to kill the session, also delete the session cookie.
  392. // Note: This will destroy the session, and not just the session data!
  393. }
  394. static function SecureConnectionRequired()
  395. {
  396. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  397. }
  398. /**
  399. * Guess if a string looks like an UTF-8 string based on some ranges of multi-bytes encoding
  400. * @param string $sString
  401. * @return bool True if the string contains some typical UTF-8 multi-byte sequences
  402. */
  403. static function LooksLikeUTF8($sString)
  404. {
  405. return preg_match('%(?:
  406. [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  407. |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  408. |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  409. |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  410. |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  411. |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  412. |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  413. )+%xs', $sString);
  414. }
  415. /**
  416. * Attempt a login
  417. *
  418. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  419. * @return int One of the class constants EXIT_CODE_...
  420. */
  421. protected static function Login($iOnExit)
  422. {
  423. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  424. {
  425. // Non secured URL... request for a secure connection
  426. throw new Exception('Secure connection required!');
  427. }
  428. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  429. if (isset($_SESSION['auth_user']))
  430. {
  431. //echo "User: ".$_SESSION['auth_user']."\n";
  432. // Already authentified
  433. $bRet = UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  434. if ($bRet)
  435. {
  436. return self::EXIT_CODE_OK;
  437. }
  438. // The user account is no longer valid/enabled
  439. static::ResetSession();
  440. }
  441. $index = 0;
  442. $sLoginMode = '';
  443. $sAuthentication = 'internal';
  444. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  445. {
  446. $sLoginType = $aAllowedLoginTypes[$index];
  447. switch($sLoginType)
  448. {
  449. case 'cas':
  450. utils::InitCASClient();
  451. // check CAS authentication
  452. if (phpCAS::isAuthenticated())
  453. {
  454. $sAuthUser = phpCAS::getUser();
  455. $sAuthPwd = '';
  456. $sLoginMode = 'cas';
  457. $sAuthentication = 'external';
  458. }
  459. break;
  460. case 'form':
  461. // iTop standard mode: form based authentication
  462. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  463. $sAuthPwd = utils::ReadPostedParam('auth_pwd', null, false, 'raw_data');
  464. if (($sAuthUser != '') && ($sAuthPwd !== null))
  465. {
  466. $sLoginMode = 'form';
  467. }
  468. break;
  469. case 'basic':
  470. // Standard PHP authentication method, works with Apache...
  471. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  472. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  473. {
  474. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  475. $sLoginMode = 'basic';
  476. }
  477. else if (isset($_SERVER['PHP_AUTH_USER']))
  478. {
  479. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  480. // Unfortunately, the RFC is not clear about the encoding...
  481. // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
  482. // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
  483. if (!self::LooksLikeUTF8($sAuthUser))
  484. {
  485. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  486. // Supposed to be harmless in case of a plain ASCII string...
  487. $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
  488. }
  489. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  490. if (!self::LooksLikeUTF8($sAuthPwd))
  491. {
  492. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  493. // Supposed to be harmless in case of a plain ASCII string...
  494. $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
  495. }
  496. $sLoginMode = 'basic';
  497. }
  498. break;
  499. case 'external':
  500. // Web server supplied authentication
  501. $bExternalAuth = false;
  502. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  503. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  504. if ($sAuthUser && (strlen($sAuthUser) > 0))
  505. {
  506. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  507. $sLoginMode = 'external';
  508. $sAuthentication = 'external';
  509. }
  510. break;
  511. case 'url':
  512. // Credentials passed directly in the url
  513. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  514. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  515. if (($sAuthUser != '') && ($sAuthPwd !== null))
  516. {
  517. $sLoginMode = 'url';
  518. }
  519. break;
  520. }
  521. $index++;
  522. }
  523. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  524. if ($sLoginMode == '')
  525. {
  526. // First connection
  527. $sDesiredLoginMode = utils::ReadParam('login_mode');
  528. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  529. {
  530. $sLoginMode = $sDesiredLoginMode;
  531. }
  532. else
  533. {
  534. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  535. }
  536. if (array_key_exists('HTTP_X_COMBODO_AJAX', $_SERVER))
  537. {
  538. // X-Combodo-Ajax is a special header automatically added to all ajax requests
  539. // Let's reply that we're currently logged-out
  540. header('HTTP/1.0 401 Unauthorized');
  541. exit;
  542. }
  543. if (($iOnExit == self::EXIT_HTTP_401) || ($sLoginMode == 'basic'))
  544. {
  545. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  546. header('HTTP/1.0 401 Unauthorized');
  547. header('Content-type: text/html; charset=iso-8859-1');
  548. exit;
  549. }
  550. else if($iOnExit == self::EXIT_RETURN)
  551. {
  552. if (($sAuthUser !== '') && ($sAuthPwd === null))
  553. {
  554. return self::EXIT_CODE_MISSINGPASSWORD;
  555. }
  556. else
  557. {
  558. return self::EXIT_CODE_MISSINGLOGIN;
  559. }
  560. }
  561. else
  562. {
  563. $oPage = self::NewLoginWebPage();
  564. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  565. $oPage->output();
  566. exit;
  567. }
  568. }
  569. else
  570. {
  571. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  572. {
  573. //echo "Check Credentials returned false for user $sAuthUser!";
  574. self::ResetSession();
  575. if (($iOnExit == self::EXIT_HTTP_401) || ($sLoginMode == 'basic'))
  576. {
  577. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  578. header('HTTP/1.0 401 Unauthorized');
  579. header('Content-type: text/html; charset=iso-8859-1');
  580. exit;
  581. }
  582. else if($iOnExit == self::EXIT_RETURN)
  583. {
  584. return self::EXIT_CODE_WRONGCREDENTIALS;
  585. }
  586. else
  587. {
  588. $oPage = self::NewLoginWebPage();
  589. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  590. $oPage->output();
  591. exit;
  592. }
  593. }
  594. else
  595. {
  596. // User is Ok, let's save it in the session and proceed with normal login
  597. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  598. if (MetaModel::GetConfig()->Get('log_usage'))
  599. {
  600. $oLog = new EventLoginUsage();
  601. $oLog->Set('userinfo', UserRights::GetUser());
  602. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  603. $oLog->Set('message', 'Successful login');
  604. $oLog->DBInsertNoReload();
  605. }
  606. $_SESSION['auth_user'] = $sAuthUser;
  607. $_SESSION['login_mode'] = $sLoginMode;
  608. UserRights::_InitSessionCache();
  609. }
  610. }
  611. return self::EXIT_CODE_OK;
  612. }
  613. /**
  614. * Overridable: depending on the user, head toward a dedicated portal
  615. * @param string|null $sRequestedPortalId
  616. * @param int $iOnExit How to complete the call: redirect or return a code
  617. */
  618. protected static function ChangeLocation($sRequestedPortalId = null, $iOnExit = self::EXIT_PROMPT)
  619. {
  620. $fStart = microtime(true);
  621. $ret = call_user_func(array(self::$sHandlerClass, 'Dispatch'), $sRequestedPortalId);
  622. if ($ret === true)
  623. {
  624. return self::EXIT_CODE_OK;
  625. }
  626. else if($ret === false)
  627. {
  628. throw new Exception('Nowhere to go??');
  629. }
  630. else
  631. {
  632. if ($iOnExit == self::EXIT_RETURN)
  633. {
  634. return self::EXIT_CODE_PORTALUSERNOTAUTHORIZED;
  635. }
  636. else
  637. {
  638. // No rights to be here, redirect to the portal
  639. header('Location: '.$ret);
  640. }
  641. }
  642. }
  643. /**
  644. * Check if the user is already authentified, if yes, then performs some additional validations:
  645. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  646. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  647. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  648. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  649. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  650. */
  651. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT)
  652. {
  653. $sRequestedPortalId = $bIsAllowedToPortalUsers ? 'legacy_portal' : 'backoffice';
  654. return self::DoLoginEx($sRequestedPortalId, $bMustBeAdmin, $iOnExit);
  655. }
  656. /**
  657. * Check if the user is already authentified, if yes, then performs some additional validations to redirect towards the desired "portal"
  658. * @param string|null $sRequestedPortalId The requested "portal" interface, null for any
  659. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  660. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  661. */
  662. static function DoLoginEx($sRequestedPortalId = null, $bMustBeAdmin = false, $iOnExit = self::EXIT_PROMPT)
  663. {
  664. $operation = utils::ReadParam('loginop', '');
  665. $sMessage = self::HandleOperations($operation); // May exit directly
  666. $iRet = self::Login($iOnExit);
  667. if ($iRet == self::EXIT_CODE_OK)
  668. {
  669. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  670. {
  671. if ($iOnExit == self::EXIT_RETURN)
  672. {
  673. return self::EXIT_CODE_MUSTBEADMIN;
  674. }
  675. else
  676. {
  677. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  678. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  679. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  680. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  681. $oP->output();
  682. exit;
  683. }
  684. }
  685. $iRet = call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $sRequestedPortalId, $iOnExit);
  686. }
  687. if ($iOnExit == self::EXIT_RETURN)
  688. {
  689. return $iRet;
  690. }
  691. else
  692. {
  693. return $sMessage;
  694. }
  695. }
  696. protected static function HandleOperations($operation)
  697. {
  698. $sMessage = ''; // most of the operations never return, but some can return a message to be displayed
  699. if ($operation == 'logoff')
  700. {
  701. if (isset($_SESSION['login_mode']))
  702. {
  703. $sLoginMode = $_SESSION['login_mode'];
  704. }
  705. else
  706. {
  707. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  708. if (count($aAllowedLoginTypes) > 0)
  709. {
  710. $sLoginMode = $aAllowedLoginTypes[0];
  711. }
  712. else
  713. {
  714. $sLoginMode = 'form';
  715. }
  716. }
  717. self::ResetSession();
  718. $oPage = self::NewLoginWebPage();
  719. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  720. $oPage->output();
  721. exit;
  722. }
  723. else if ($operation == 'forgot_pwd')
  724. {
  725. $oPage = self::NewLoginWebPage();
  726. $oPage->DisplayForgotPwdForm();
  727. $oPage->output();
  728. exit;
  729. }
  730. else if ($operation == 'forgot_pwd_go')
  731. {
  732. $oPage = self::NewLoginWebPage();
  733. $oPage->ForgotPwdGo();
  734. $oPage->output();
  735. exit;
  736. }
  737. else if ($operation == 'reset_pwd')
  738. {
  739. $oPage = self::NewLoginWebPage();
  740. $oPage->DisplayResetPwdForm();
  741. $oPage->output();
  742. exit;
  743. }
  744. else if ($operation == 'do_reset_pwd')
  745. {
  746. $oPage = self::NewLoginWebPage();
  747. $oPage->DoResetPassword();
  748. $oPage->output();
  749. exit;
  750. }
  751. else if ($operation == 'change_pwd')
  752. {
  753. $sAuthUser = $_SESSION['auth_user'];
  754. UserRights::Login($sAuthUser); // Set the user's language
  755. $oPage = self::NewLoginWebPage();
  756. $oPage->DisplayChangePwdForm();
  757. $oPage->output();
  758. exit;
  759. }
  760. if ($operation == 'do_change_pwd')
  761. {
  762. $sAuthUser = $_SESSION['auth_user'];
  763. UserRights::Login($sAuthUser); // Set the user's language
  764. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  765. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  766. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  767. {
  768. $oPage = self::NewLoginWebPage();
  769. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  770. $oPage->output();
  771. exit;
  772. }
  773. $sMessage = Dict::S('UI:Login:PasswordChanged');
  774. }
  775. return $sMessage;
  776. }
  777. protected static function Dispatch($sRequestedPortalId)
  778. {
  779. if ($sRequestedPortalId === null) return true; // allowed to any portal => return true
  780. $aPortalsConf = PortalDispatcherData::GetData();
  781. $aDispatchers = array();
  782. foreach($aPortalsConf as $sPortalId => $aConf)
  783. {
  784. $sHandlerClass = $aConf['handler'];
  785. $aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
  786. }
  787. if (array_key_exists($sRequestedPortalId, $aDispatchers) && $aDispatchers[$sRequestedPortalId]->IsUserAllowed())
  788. {
  789. return true;
  790. }
  791. foreach($aDispatchers as $sPortalId => $oDispatcher)
  792. {
  793. if ($oDispatcher->IsUserAllowed()) return $oDispatcher->GetUrl();
  794. }
  795. return false; // nothing matched !!
  796. }
  797. } // End of class