loginwebpage.class.inc.php 31 KB

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