loginwebpage.class.inc.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class LoginWebPage
  20. *
  21. * @copyright Copyright (C) 2010-2013 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once(APPROOT."/application/nicewebpage.class.inc.php");
  25. 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("../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. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  277. {
  278. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  279. }
  280. else
  281. {
  282. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-EnterPassword', $oUser->GetFriendlyName())."</p>\n");
  283. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  284. $this->add_script(
  285. <<<EOF
  286. function DoCheckPwd()
  287. {
  288. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  289. {
  290. alert('$sInconsistenPwdMsg');
  291. return false;
  292. }
  293. return true;
  294. }
  295. EOF
  296. );
  297. $this->add("<form method=\"post\">\n");
  298. $this->add("<table>\n");
  299. $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");
  300. $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");
  301. $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");
  302. $this->add("</table>\n");
  303. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_reset_pwd\" />\n");
  304. $this->add("<input type=\"hidden\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" />\n");
  305. $this->add("<input type=\"hidden\" name=\"token\" value=\"".htmlentities($sToken, ENT_QUOTES, 'UTF-8')."\" />\n");
  306. $this->add("</form>\n");
  307. $this->add("</div\n");
  308. }
  309. }
  310. public function DoResetPassword()
  311. {
  312. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  313. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  314. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  315. UserRights::Login($sAuthUser); // Set the user's language
  316. $oUser = UserRights::GetUserObject();
  317. $this->DisplayLoginHeader();
  318. $this->add("<div id=\"login\">\n");
  319. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  320. if ($oUser == null)
  321. {
  322. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  323. }
  324. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  325. {
  326. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  327. }
  328. else
  329. {
  330. // Trash the token and change the password
  331. $oUser->Set('reset_pwd_token', '');
  332. $oUser->SetPassword($sNewPwd); // Does record the change into the DB
  333. $this->add("<p>".Dict::S('UI:ResetPwd-Ready')."</p>");
  334. $sUrl = utils::GetAbsoluteUrlAppRoot();
  335. $this->add("<p><a href=\"$sUrl\">".Dict::S('UI:ResetPwd-Login')."</a></p>");
  336. }
  337. $this->add("</div\n");
  338. }
  339. public function DisplayChangePwdForm($bFailedLogin = false)
  340. {
  341. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  342. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  343. $this->add_script(<<<EOF
  344. function GoBack()
  345. {
  346. window.history.back();
  347. }
  348. function DoCheckPwd()
  349. {
  350. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  351. {
  352. alert('$sInconsistenPwdMsg');
  353. return false;
  354. }
  355. return true;
  356. }
  357. EOF
  358. );
  359. $this->DisplayLoginHeader();
  360. $this->add("<div id=\"login\">\n");
  361. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  362. if ($bFailedLogin)
  363. {
  364. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  365. }
  366. $this->add("<form method=\"post\">\n");
  367. $this->add("<table>\n");
  368. $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");
  369. $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");
  370. $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");
  371. $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");
  372. $this->add("</table>\n");
  373. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  374. $this->add("</form>\n");
  375. $this->add("</div>\n");
  376. }
  377. static function ResetSession()
  378. {
  379. // Unset all of the session variables.
  380. unset($_SESSION['auth_user']);
  381. unset($_SESSION['login_mode']);
  382. UserRights::_ResetSessionCache();
  383. // If it's desired to kill the session, also delete the session cookie.
  384. // Note: This will destroy the session, and not just the session data!
  385. }
  386. static function SecureConnectionRequired()
  387. {
  388. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  389. }
  390. /**
  391. * Guess if a string looks like an UTF-8 string based on some ranges of multi-bytes encoding
  392. * @param string $sString
  393. * @return bool True if the string contains some typical UTF-8 multi-byte sequences
  394. */
  395. static function LooksLikeUTF8($sString)
  396. {
  397. return preg_match('%(?:
  398. [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  399. |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  400. |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  401. |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  402. |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  403. |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  404. |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  405. )+%xs', $sString);
  406. }
  407. /**
  408. * Attempt a login
  409. *
  410. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  411. * @return int One of the class constants EXIT_CODE_...
  412. */
  413. protected static function Login($iOnExit)
  414. {
  415. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  416. {
  417. // Non secured URL... request for a secure connection
  418. throw new Exception('Secure connection required!');
  419. }
  420. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  421. if (isset($_SESSION['auth_user']))
  422. {
  423. //echo "User: ".$_SESSION['auth_user']."\n";
  424. // Already authentified
  425. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  426. return self::EXIT_CODE_OK;
  427. }
  428. else
  429. {
  430. $index = 0;
  431. $sLoginMode = '';
  432. $sAuthentication = 'internal';
  433. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  434. {
  435. $sLoginType = $aAllowedLoginTypes[$index];
  436. switch($sLoginType)
  437. {
  438. case 'cas':
  439. utils::InitCASClient();
  440. // check CAS authentication
  441. if (phpCAS::isAuthenticated())
  442. {
  443. $sAuthUser = phpCAS::getUser();
  444. $sAuthPwd = '';
  445. $sLoginMode = 'cas';
  446. $sAuthentication = 'external';
  447. }
  448. break;
  449. case 'form':
  450. // iTop standard mode: form based authentication
  451. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  452. $sAuthPwd = utils::ReadPostedParam('auth_pwd', null, false, 'raw_data');
  453. if (($sAuthUser != '') && ($sAuthPwd !== null))
  454. {
  455. $sLoginMode = 'form';
  456. }
  457. break;
  458. case 'basic':
  459. // Standard PHP authentication method, works with Apache...
  460. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  461. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  462. {
  463. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  464. $sLoginMode = 'basic';
  465. }
  466. else if (isset($_SERVER['PHP_AUTH_USER']))
  467. {
  468. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  469. // Unfortunately, the RFC is not clear about the encoding...
  470. // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
  471. // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
  472. if (!self::LooksLikeUTF8($sAuthUser))
  473. {
  474. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  475. // Supposed to be harmless in case of a plain ASCII string...
  476. $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
  477. }
  478. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  479. if (!self::LooksLikeUTF8($sAuthPwd))
  480. {
  481. // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
  482. // Supposed to be harmless in case of a plain ASCII string...
  483. $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
  484. }
  485. $sLoginMode = 'basic';
  486. }
  487. break;
  488. case 'external':
  489. // Web server supplied authentication
  490. $bExternalAuth = false;
  491. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  492. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  493. if ($sAuthUser && (strlen($sAuthUser) > 0))
  494. {
  495. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  496. $sLoginMode = 'external';
  497. $sAuthentication = 'external';
  498. }
  499. break;
  500. case 'url':
  501. // Credentials passed directly in the url
  502. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  503. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  504. if (($sAuthUser != '') && ($sAuthPwd !== null))
  505. {
  506. $sLoginMode = 'url';
  507. }
  508. break;
  509. }
  510. $index++;
  511. }
  512. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  513. if ($sLoginMode == '')
  514. {
  515. // First connection
  516. $sDesiredLoginMode = utils::ReadParam('login_mode');
  517. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  518. {
  519. $sLoginMode = $sDesiredLoginMode;
  520. }
  521. else
  522. {
  523. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  524. }
  525. if (array_key_exists('HTTP_X_COMBODO_AJAX', $_SERVER))
  526. {
  527. // X-Combodo-Ajax is a special header automatically added to all ajax requests
  528. // Let's reply that we're currently logged-out
  529. header('HTTP/1.0 401 Unauthorized');
  530. exit;
  531. }
  532. if (($iOnExit == self::EXIT_HTTP_401) || ($sLoginMode == 'basic'))
  533. {
  534. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  535. header('HTTP/1.0 401 Unauthorized');
  536. header('Content-type: text/html; charset=iso-8859-1');
  537. exit;
  538. }
  539. else if($iOnExit == self::EXIT_RETURN)
  540. {
  541. if (($sAuthUser !== '') && ($sAuthPwd === null))
  542. {
  543. return self::EXIT_CODE_MISSINGPASSWORD;
  544. }
  545. else
  546. {
  547. return self::EXIT_CODE_MISSINGLOGIN;
  548. }
  549. }
  550. else
  551. {
  552. $oPage = self::NewLoginWebPage();
  553. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  554. $oPage->output();
  555. exit;
  556. }
  557. }
  558. else
  559. {
  560. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  561. {
  562. //echo "Check Credentials returned false for user $sAuthUser!";
  563. self::ResetSession();
  564. if (($iOnExit == self::EXIT_HTTP_401) || ($sLoginMode == 'basic'))
  565. {
  566. header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  567. header('HTTP/1.0 401 Unauthorized');
  568. header('Content-type: text/html; charset=iso-8859-1');
  569. exit;
  570. }
  571. else if($iOnExit == self::EXIT_RETURN)
  572. {
  573. return self::EXIT_CODE_WRONGCREDENTIALS;
  574. }
  575. else
  576. {
  577. $oPage = self::NewLoginWebPage();
  578. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  579. $oPage->output();
  580. exit;
  581. }
  582. }
  583. else
  584. {
  585. // User is Ok, let's save it in the session and proceed with normal login
  586. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  587. if (MetaModel::GetConfig()->Get('log_usage'))
  588. {
  589. $oLog = new EventLoginUsage();
  590. $oLog->Set('userinfo', UserRights::GetUser());
  591. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  592. $oLog->Set('message', 'Successful login');
  593. $oLog->DBInsertNoReload();
  594. }
  595. $_SESSION['auth_user'] = $sAuthUser;
  596. $_SESSION['login_mode'] = $sLoginMode;
  597. UserRights::_InitSessionCache();
  598. }
  599. }
  600. }
  601. return self::EXIT_CODE_OK;
  602. }
  603. /**
  604. * Overridable: depending on the user, head toward a dedicated portal
  605. * @param string|null $sRequestedPortalId
  606. * @param int $iOnExit How to complete the call: redirect or return a code
  607. */
  608. protected static function ChangeLocation($sRequestedPortalId = null, $iOnExit = self::EXIT_PROMPT)
  609. {
  610. $fStart = microtime(true);
  611. $ret = call_user_func(array(self::$sHandlerClass, 'Dispatch'), $sRequestedPortalId);
  612. if ($ret === true)
  613. {
  614. return self::EXIT_CODE_OK;
  615. }
  616. else if($ret === false)
  617. {
  618. throw new Exception('Nowhere to go??');
  619. }
  620. else
  621. {
  622. if ($iOnExit == self::EXIT_RETURN)
  623. {
  624. return self::EXIT_CODE_PORTALUSERNOTAUTHORIZED;
  625. }
  626. else
  627. {
  628. // No rights to be here, redirect to the portal
  629. header('Location: '.$ret);
  630. }
  631. }
  632. }
  633. /**
  634. * Check if the user is already authentified, if yes, then performs some additional validations:
  635. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  636. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  637. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  638. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  639. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  640. */
  641. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT)
  642. {
  643. $sRequestedPortalId = $bIsAllowedToPortalUsers ? 'legacy_portal' : 'backoffice';
  644. return self::DoLoginEx($sRequestedPortalId, $bMustBeAdmin, $iOnExit);
  645. }
  646. /**
  647. * Check if the user is already authentified, if yes, then performs some additional validations to redirect towards the desired "portal"
  648. * @param string|null $sRequestedPortalId The requested "portal" interface, null for any
  649. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  650. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  651. */
  652. static function DoLoginEx($sRequestedPortalId = null, $bMustBeAdmin = false, $iOnExit = self::EXIT_PROMPT)
  653. {
  654. $operation = utils::ReadParam('loginop', '');
  655. $sMessage = self::HandleOperations($operation); // May exit directly
  656. $iRet = self::Login($iOnExit);
  657. if ($iRet == self::EXIT_CODE_OK)
  658. {
  659. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  660. {
  661. if ($iOnExit == self::EXIT_RETURN)
  662. {
  663. return self::EXIT_CODE_MUSTBEADMIN;
  664. }
  665. else
  666. {
  667. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  668. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  669. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  670. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  671. $oP->output();
  672. exit;
  673. }
  674. }
  675. $iRet = call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $sRequestedPortalId, $iOnExit);
  676. }
  677. if ($iOnExit == self::EXIT_RETURN)
  678. {
  679. return $iRet;
  680. }
  681. else
  682. {
  683. return $sMessage;
  684. }
  685. }
  686. protected static function HandleOperations($operation)
  687. {
  688. $sMessage = ''; // most of the operations never return, but some can return a message to be displayed
  689. if ($operation == 'logoff')
  690. {
  691. if (isset($_SESSION['login_mode']))
  692. {
  693. $sLoginMode = $_SESSION['login_mode'];
  694. }
  695. else
  696. {
  697. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  698. if (count($aAllowedLoginTypes) > 0)
  699. {
  700. $sLoginMode = $aAllowedLoginTypes[0];
  701. }
  702. else
  703. {
  704. $sLoginMode = 'form';
  705. }
  706. }
  707. self::ResetSession();
  708. $oPage = self::NewLoginWebPage();
  709. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  710. $oPage->output();
  711. exit;
  712. }
  713. else if ($operation == 'forgot_pwd')
  714. {
  715. $oPage = self::NewLoginWebPage();
  716. $oPage->DisplayForgotPwdForm();
  717. $oPage->output();
  718. exit;
  719. }
  720. else if ($operation == 'forgot_pwd_go')
  721. {
  722. $oPage = self::NewLoginWebPage();
  723. $oPage->ForgotPwdGo();
  724. $oPage->output();
  725. exit;
  726. }
  727. else if ($operation == 'reset_pwd')
  728. {
  729. $oPage = self::NewLoginWebPage();
  730. $oPage->DisplayResetPwdForm();
  731. $oPage->output();
  732. exit;
  733. }
  734. else if ($operation == 'do_reset_pwd')
  735. {
  736. $oPage = self::NewLoginWebPage();
  737. $oPage->DoResetPassword();
  738. $oPage->output();
  739. exit;
  740. }
  741. else if ($operation == 'change_pwd')
  742. {
  743. $sAuthUser = $_SESSION['auth_user'];
  744. UserRights::Login($sAuthUser); // Set the user's language
  745. $oPage = self::NewLoginWebPage();
  746. $oPage->DisplayChangePwdForm();
  747. $oPage->output();
  748. exit;
  749. }
  750. if ($operation == 'do_change_pwd')
  751. {
  752. $sAuthUser = $_SESSION['auth_user'];
  753. UserRights::Login($sAuthUser); // Set the user's language
  754. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  755. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  756. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  757. {
  758. $oPage = self::NewLoginWebPage();
  759. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  760. $oPage->output();
  761. exit;
  762. }
  763. $sMessage = Dict::S('UI:Login:PasswordChanged');
  764. }
  765. return $sMessage;
  766. }
  767. protected static function Dispatch($sRequestedPortalId)
  768. {
  769. if ($sRequestedPortalId === null) return true; // allowed to any portal => return true
  770. $aPortalsConf = PortalDispatcherData::GetData();
  771. $aDispatchers = array();
  772. foreach($aPortalsConf as $sPortalId => $aConf)
  773. {
  774. $sHandlerClass = $aConf['handler'];
  775. $aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
  776. }
  777. if (array_key_exists($sRequestedPortalId, $aDispatchers) && $aDispatchers[$sRequestedPortalId]->IsUserAllowed())
  778. {
  779. return true;
  780. }
  781. foreach($aDispatchers as $sPortalId => $oDispatcher)
  782. {
  783. if ($oDispatcher->IsUserAllowed()) return $oDispatcher->GetUrl();
  784. }
  785. return false; // nothing matched !!
  786. }
  787. public static function GetAllowedPortals()
  788. {
  789. $aAllowedPortals = array();
  790. $aPortalsConf = PortalDispatcherData::GetData();
  791. $aDispatchers = array();
  792. foreach($aPortalsConf as $sPortalId => $aConf)
  793. {
  794. $sHandlerClass = $aConf['handler'];
  795. $aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
  796. }
  797. foreach($aDispatchers as $sPortalId => $oDispatcher)
  798. {
  799. if ($oDispatcher->IsUserAllowed())
  800. {
  801. $aAllowedPortals[] = array(
  802. 'id' => $sPortalId,
  803. 'label' => $oDispatcher->GetLabel(),
  804. 'url' => $oDispatcher->GetUrl(),
  805. );
  806. }
  807. }
  808. return $aAllowedPortals;
  809. }
  810. } // End of class