loginwebpage.class.inc.php 28 KB

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