loginwebpage.class.inc.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. protected static $sHandlerClass = __class__;
  33. public static function RegisterHandler($sClass)
  34. {
  35. self::$sHandlerClass = $sClass;
  36. }
  37. public static function NewLoginWebPage()
  38. {
  39. return new self::$sHandlerClass;
  40. }
  41. protected static $m_sLoginFailedMessage = '';
  42. public function __construct($sTitle = 'iTop Login')
  43. {
  44. parent::__construct($sTitle);
  45. $this->SetStyleSheet();
  46. $this->add_header("Cache-control: no-cache");
  47. }
  48. public function SetStyleSheet()
  49. {
  50. $this->add_linked_stylesheet("../css/login.css");
  51. }
  52. public static function SetLoginFailedMessage($sMessage)
  53. {
  54. self::$m_sLoginFailedMessage = $sMessage;
  55. }
  56. public function EnableResetPassword()
  57. {
  58. return MetaModel::GetConfig()->Get('forgot_password');
  59. }
  60. public function DisplayLoginHeader($bMainAppLogo = false)
  61. {
  62. if ($bMainAppLogo)
  63. {
  64. $sLogo = 'itop-logo.png';
  65. $sBrandingLogo = 'main-logo.png';
  66. }
  67. else
  68. {
  69. $sLogo = 'itop-logo-external.png';
  70. $sBrandingLogo = 'login-logo.png';
  71. }
  72. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  73. $sIconUrl = Utils::GetConfig()->Get('app_icon_url');
  74. $sDisplayIcon = utils::GetAbsoluteUrlAppRoot().'images/'.$sLogo;
  75. if (file_exists(MODULESROOT.'branding/'.$sBrandingLogo))
  76. {
  77. $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot().'branding/'.$sBrandingLogo;
  78. }
  79. $this->add("<div id=\"login-logo\"><a href=\"".htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8')."\"><img title=\"$sVersionShort\" src=\"$sDisplayIcon\"></a></div>\n");
  80. }
  81. public function DisplayLoginForm($sLoginType, $bFailedLogin = false)
  82. {
  83. switch($sLoginType)
  84. {
  85. case 'cas':
  86. utils::InitCASClient();
  87. // force CAS authentication
  88. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  89. break;
  90. case 'basic':
  91. case 'url':
  92. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  93. $this->add_header('HTTP/1.0 401 Unauthorized');
  94. // Note: displayed when the user will click on Cancel
  95. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  96. break;
  97. case 'external':
  98. case 'form':
  99. default: // In case the settings get messed up...
  100. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  101. $sAuthPwd = utils::ReadParam('suggest_pwd', '', true, 'raw_data');
  102. $this->DisplayLoginHeader();
  103. $this->add("<div id=\"login\">\n");
  104. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  105. if ($bFailedLogin)
  106. {
  107. if (self::$m_sLoginFailedMessage != '')
  108. {
  109. $this->add("<p class=\"hilite\">".self::$m_sLoginFailedMessage."</p>\n");
  110. }
  111. else
  112. {
  113. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  114. }
  115. }
  116. else
  117. {
  118. $this->add("<p>".Dict::S('UI:Login:IdentifyYourself')."</p>\n");
  119. }
  120. $this->add("<form method=\"post\">\n");
  121. $this->add("<table>\n");
  122. $sForgotPwd = $this->EnableResetPassword() ? $this->ForgotPwdLink() : '';
  123. $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");
  124. $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");
  125. $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");
  126. if (strlen($sForgotPwd) > 0)
  127. {
  128. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\">$sForgotPwd</td></tr>\n");
  129. }
  130. $this->add("</table>\n");
  131. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  132. // Keep the OTHER parameters posted
  133. foreach($_POST as $sPostedKey => $postedValue)
  134. {
  135. if (!in_array($sPostedKey, array('auth_user', 'auth_pwd')))
  136. {
  137. if (is_array($postedValue))
  138. {
  139. foreach($postedValue as $sKey => $sValue)
  140. {
  141. $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");
  142. }
  143. }
  144. else
  145. {
  146. $this->add("<input type=\"hidden\" name=\"".htmlentities($sPostedKey, ENT_QUOTES, 'UTF-8')."\" value=\"".htmlentities($postedValue, ENT_QUOTES, 'UTF-8')."\" />\n");
  147. }
  148. }
  149. }
  150. $this->add("</form>\n");
  151. $this->add(Dict::S('UI:Login:About'));
  152. $this->add("</div>\n");
  153. break;
  154. }
  155. }
  156. /**
  157. * Return '' to disable this feature
  158. */
  159. public function ForgotPwdLink()
  160. {
  161. $sUrl = '?loginop=forgot_pwd';
  162. $sHtml = "<a href=\"$sUrl\" target=\"_blank\">".Dict::S('UI:Login:ForgotPwd')."</a>";
  163. return $sHtml;
  164. }
  165. public function DisplayForgotPwdForm($bFailedToReset = false, $sFailureReason = null)
  166. {
  167. $this->DisplayLoginHeader();
  168. $this->add("<div id=\"login\">\n");
  169. $this->add("<h1>".Dict::S('UI:Login:ForgotPwdForm')."</h1>\n");
  170. $this->add("<p>".Dict::S('UI:Login:ForgotPwdForm+')."</p>\n");
  171. if ($bFailedToReset)
  172. {
  173. $this->add("<p class=\"hilite\">".Dict::Format('UI:Login:ResetPwdFailed', $sFailureReason)."</p>\n");
  174. }
  175. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  176. $this->add("<form method=\"post\">\n");
  177. $this->add("<table>\n");
  178. $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");
  179. $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:Button:ResetPassword')."\" /></span></td></tr>\n");
  180. $this->add("</table>\n");
  181. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"forgot_pwd_go\" />\n");
  182. $this->add("</form>\n");
  183. $this->add("</div>\n");
  184. }
  185. protected function ForgotPwdGo()
  186. {
  187. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  188. try
  189. {
  190. UserRights::Login($sAuthUser); // Set the user's language (if possible!)
  191. $oUser = UserRights::GetUserObject();
  192. if ($oUser == null)
  193. {
  194. throw new Exception(Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser));
  195. }
  196. if (!MetaModel::IsValidAttCode(get_class($oUser), 'reset_pwd_token'))
  197. {
  198. throw new Exception(Dict::S('UI:ResetPwd-Error-NotPossible'));
  199. }
  200. if (!$oUser->CanChangePassword())
  201. {
  202. throw new Exception(Dict::S('UI:ResetPwd-Error-FixedPwd'));
  203. }
  204. $sTo = $oUser->GetResetPasswordEmail(); // throws Exceptions if not allowed
  205. if ($sTo == '')
  206. {
  207. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmail'));
  208. }
  209. // This token allows the user to change the password without knowing the previous one
  210. $sToken = substr(md5(APPROOT.uniqid()), 0, 16);
  211. $oUser->Set('reset_pwd_token', $sToken);
  212. CMDBObject::SetTrackInfo('Reset password');
  213. $oUser->DBUpdate();
  214. $oEmail = new Email();
  215. $oEmail->SetRecipientTO($sTo);
  216. $oEmail->SetRecipientFrom($sTo);
  217. $oEmail->SetSubject(Dict::S('UI:ResetPwd-EmailSubject'));
  218. $sResetUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?loginop=reset_pwd&auth_user='.urlencode($oUser->Get('login')).'&token='.urlencode($sToken);
  219. $oEmail->SetBody(Dict::Format('UI:ResetPwd-EmailBody', $sResetUrl));
  220. $iRes = $oEmail->Send($aIssues, true /* force synchronous exec */);
  221. switch ($iRes)
  222. {
  223. //case EMAIL_SEND_PENDING:
  224. case EMAIL_SEND_OK:
  225. break;
  226. case EMAIL_SEND_ERROR:
  227. default:
  228. IssueLog::Error('Failed to send the email with the NEW password for '.$oUser->Get('friendlyname').': '.implode(', ', $aIssues));
  229. throw new Exception(Dict::S('UI:ResetPwd-Error-Send'));
  230. }
  231. $this->DisplayLoginHeader();
  232. $this->add("<div id=\"login\">\n");
  233. $this->add("<h1>".Dict::S('UI:Login:ForgotPwdForm')."</h1>\n");
  234. $this->add("<p>".Dict::S('UI:ResetPwd-EmailSent')."</p>");
  235. $this->add("<form method=\"post\">\n");
  236. $this->add("<table>\n");
  237. $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");
  238. $this->add("</table>\n");
  239. $this->add("</form>\n");
  240. $this->add("</div\n");
  241. }
  242. catch(Exception $e)
  243. {
  244. $this->DisplayForgotPwdForm(true, $e->getMessage());
  245. }
  246. }
  247. public function DisplayResetPwdForm()
  248. {
  249. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  250. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  251. UserRights::Login($sAuthUser); // Set the user's language
  252. $oUser = UserRights::GetUserObject();
  253. $this->DisplayLoginHeader();
  254. $this->add("<div id=\"login\">\n");
  255. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  256. if ($oUser == null)
  257. {
  258. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  259. }
  260. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  261. {
  262. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  263. }
  264. else
  265. {
  266. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-EnterPassword', $oUser->GetFriendlyName())."</p>\n");
  267. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  268. $this->add_script(
  269. <<<EOF
  270. function DoCheckPwd()
  271. {
  272. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  273. {
  274. alert('$sInconsistenPwdMsg');
  275. return false;
  276. }
  277. return true;
  278. }
  279. EOF
  280. );
  281. $this->add("<form method=\"post\">\n");
  282. $this->add("<table>\n");
  283. $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");
  284. $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");
  285. $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");
  286. $this->add("</table>\n");
  287. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_reset_pwd\" />\n");
  288. $this->add("<input type=\"hidden\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" />\n");
  289. $this->add("<input type=\"hidden\" name=\"token\" value=\"".htmlentities($sToken, ENT_QUOTES, 'UTF-8')."\" />\n");
  290. $this->add("</form>\n");
  291. $this->add("</div\n");
  292. }
  293. }
  294. public function DoResetPassword()
  295. {
  296. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  297. $sToken = utils::ReadParam('token', '', false, 'raw_data');
  298. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  299. UserRights::Login($sAuthUser); // Set the user's language
  300. $oUser = UserRights::GetUserObject();
  301. $this->DisplayLoginHeader();
  302. $this->add("<div id=\"login\">\n");
  303. $this->add("<h1>".Dict::S('UI:ResetPwd-Title')."</h1>\n");
  304. if ($oUser == null)
  305. {
  306. $this->add("<p>".Dict::Format('UI:ResetPwd-Error-WrongLogin', $sAuthUser)."</p>\n");
  307. }
  308. elseif ($oUser->Get('reset_pwd_token') != $sToken)
  309. {
  310. $this->add("<p>".Dict::S('UI:ResetPwd-Error-InvalidToken')."</p>\n");
  311. }
  312. else
  313. {
  314. // Trash the token and change the password
  315. $oUser->Set('reset_pwd_token', '');
  316. $oUser->SetPassword($sNewPwd); // Does record the change into the DB
  317. $this->add("<p>".Dict::S('UI:ResetPwd-Ready')."</p>");
  318. $sUrl = utils::GetAbsoluteUrlAppRoot();
  319. $this->add("<p><a href=\"$sUrl\">".Dict::S('UI:ResetPwd-Login')."</a></p>");
  320. }
  321. $this->add("</div\n");
  322. }
  323. public function DisplayChangePwdForm($bFailedLogin = false)
  324. {
  325. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  326. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  327. $this->add_script(<<<EOF
  328. function GoBack()
  329. {
  330. window.history.back();
  331. }
  332. function DoCheckPwd()
  333. {
  334. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  335. {
  336. alert('$sInconsistenPwdMsg');
  337. return false;
  338. }
  339. return true;
  340. }
  341. EOF
  342. );
  343. $this->DisplayLoginHeader();
  344. $this->add("<div id=\"login\">\n");
  345. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  346. if ($bFailedLogin)
  347. {
  348. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  349. }
  350. $this->add("<form method=\"post\">\n");
  351. $this->add("<table>\n");
  352. $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");
  353. $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");
  354. $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");
  355. $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");
  356. $this->add("</table>\n");
  357. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  358. $this->add("</form>\n");
  359. $this->add("</div>\n");
  360. }
  361. static function ResetSession()
  362. {
  363. if (isset($_SESSION['login_mode']))
  364. {
  365. $sPreviousLoginMode = $_SESSION['login_mode'];
  366. }
  367. else
  368. {
  369. $sPreviousLoginMode = '';
  370. }
  371. // Unset all of the session variables.
  372. unset($_SESSION['auth_user']);
  373. unset($_SESSION['login_mode']);
  374. // If it's desired to kill the session, also delete the session cookie.
  375. // Note: This will destroy the session, and not just the session data!
  376. }
  377. static function SecureConnectionRequired()
  378. {
  379. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  380. }
  381. /**
  382. * Attempt a login
  383. *
  384. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  385. */
  386. protected static function Login($iOnExit)
  387. {
  388. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  389. {
  390. // Non secured URL... request for a secure connection
  391. throw new Exception('Secure connection required!');
  392. }
  393. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  394. if (isset($_SESSION['auth_user']))
  395. {
  396. //echo "User: ".$_SESSION['auth_user']."\n";
  397. // Already authentified
  398. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  399. return true;
  400. }
  401. else
  402. {
  403. $index = 0;
  404. $sLoginMode = '';
  405. $sAuthentication = 'internal';
  406. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  407. {
  408. $sLoginType = $aAllowedLoginTypes[$index];
  409. switch($sLoginType)
  410. {
  411. case 'cas':
  412. utils::InitCASClient();
  413. // check CAS authentication
  414. if (phpCAS::isAuthenticated())
  415. {
  416. $sAuthUser = phpCAS::getUser();
  417. $sAuthPwd = '';
  418. $sLoginMode = 'cas';
  419. $sAuthentication = 'external';
  420. }
  421. break;
  422. case 'form':
  423. // iTop standard mode: form based authentication
  424. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  425. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', false, 'raw_data');
  426. if ($sAuthUser != '')
  427. {
  428. $sLoginMode = 'form';
  429. }
  430. break;
  431. case 'basic':
  432. // Standard PHP authentication method, works with Apache...
  433. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  434. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  435. {
  436. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  437. $sLoginMode = 'basic';
  438. }
  439. else if (isset($_SERVER['PHP_AUTH_USER']))
  440. {
  441. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  442. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  443. $sLoginMode = 'basic';
  444. }
  445. break;
  446. case 'external':
  447. // Web server supplied authentication
  448. $bExternalAuth = false;
  449. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  450. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  451. if ($sAuthUser && (strlen($sAuthUser) > 0))
  452. {
  453. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  454. $sLoginMode = 'external';
  455. $sAuthentication = 'external';
  456. }
  457. break;
  458. case 'url':
  459. // Credentials passed directly in the url
  460. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  461. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  462. if (($sAuthUser != '') && ($sAuthPwd != null))
  463. {
  464. $sLoginMode = 'url';
  465. }
  466. break;
  467. }
  468. $index++;
  469. }
  470. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  471. if ($sLoginMode == '')
  472. {
  473. // First connection
  474. $sDesiredLoginMode = utils::ReadParam('login_mode');
  475. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  476. {
  477. $sLoginMode = $sDesiredLoginMode;
  478. }
  479. else
  480. {
  481. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  482. }
  483. if ($iOnExit == self::EXIT_HTTP_401)
  484. {
  485. header("HTTP/1.0 401 Unauthorized");
  486. exit;
  487. }
  488. else
  489. {
  490. $oPage = self::NewLoginWebPage();
  491. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  492. $oPage->output();
  493. exit;
  494. }
  495. }
  496. else
  497. {
  498. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  499. {
  500. //echo "Check Credentials returned false for user $sAuthUser!";
  501. self::ResetSession();
  502. if ($iOnExit == self::EXIT_HTTP_401)
  503. {
  504. header("HTTP/1.0 401 Unauthorized");
  505. exit;
  506. }
  507. else
  508. {
  509. $oPage = self::NewLoginWebPage();
  510. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  511. $oPage->output();
  512. exit;
  513. }
  514. }
  515. else
  516. {
  517. // User is Ok, let's save it in the session and proceed with normal login
  518. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  519. if (MetaModel::GetConfig()->Get('log_usage'))
  520. {
  521. $oLog = new EventLoginUsage();
  522. $oLog->Set('userinfo', UserRights::GetUser());
  523. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  524. $oLog->Set('message', 'Successful login');
  525. $oLog->DBInsertNoReload();
  526. }
  527. $_SESSION['auth_user'] = $sAuthUser;
  528. $_SESSION['login_mode'] = $sLoginMode;
  529. }
  530. }
  531. }
  532. }
  533. /**
  534. * Overridable: depending on the user, head toward a dedicated portal
  535. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  536. */
  537. protected static function ChangeLocation($bIsAllowedToPortalUsers)
  538. {
  539. if ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  540. {
  541. // No rights to be here, redirect to the portal
  542. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  543. }
  544. }
  545. /**
  546. * Check if the user is already authentified, if yes, then performs some additional validations:
  547. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  548. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  549. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  550. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  551. * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...)
  552. */
  553. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false, $iOnExit = self::EXIT_PROMPT)
  554. {
  555. $sMessage = ''; // In case we need to return a message to the calling web page
  556. $operation = utils::ReadParam('loginop', '');
  557. if ($operation == 'logoff')
  558. {
  559. if (isset($_SESSION['login_mode']))
  560. {
  561. $sLoginMode = $_SESSION['login_mode'];
  562. }
  563. else
  564. {
  565. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  566. if (count($aAllowedLoginTypes) > 0)
  567. {
  568. $sLoginMode = $aAllowedLoginTypes[0];
  569. }
  570. else
  571. {
  572. $sLoginMode = 'form';
  573. }
  574. }
  575. self::ResetSession();
  576. $oPage = self::NewLoginWebPage();
  577. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  578. $oPage->output();
  579. exit;
  580. }
  581. else if ($operation == 'forgot_pwd')
  582. {
  583. $oPage = self::NewLoginWebPage();
  584. $oPage->DisplayForgotPwdForm();
  585. $oPage->output();
  586. exit;
  587. }
  588. else if ($operation == 'forgot_pwd_go')
  589. {
  590. $oPage = self::NewLoginWebPage();
  591. $oPage->ForgotPwdGo();
  592. $oPage->output();
  593. exit;
  594. }
  595. else if ($operation == 'reset_pwd')
  596. {
  597. $oPage = self::NewLoginWebPage();
  598. $oPage->DisplayResetPwdForm();
  599. $oPage->output();
  600. exit;
  601. }
  602. else if ($operation == 'do_reset_pwd')
  603. {
  604. $oPage = self::NewLoginWebPage();
  605. $oPage->DoResetPassword();
  606. $oPage->output();
  607. exit;
  608. }
  609. else if ($operation == 'change_pwd')
  610. {
  611. $sAuthUser = $_SESSION['auth_user'];
  612. UserRights::Login($sAuthUser); // Set the user's language
  613. $oPage = self::NewLoginWebPage();
  614. $oPage->DisplayChangePwdForm();
  615. $oPage->output();
  616. exit;
  617. }
  618. if ($operation == 'do_change_pwd')
  619. {
  620. $sAuthUser = $_SESSION['auth_user'];
  621. UserRights::Login($sAuthUser); // Set the user's language
  622. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  623. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  624. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  625. {
  626. $oPage = self::NewLoginWebPage();
  627. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  628. $oPage->output();
  629. exit;
  630. }
  631. $sMessage = Dict::S('UI:Login:PasswordChanged');
  632. }
  633. self::Login($iOnExit);
  634. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  635. {
  636. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  637. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  638. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  639. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  640. $oP->output();
  641. exit;
  642. }
  643. call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $bIsAllowedToPortalUsers);
  644. return $sMessage;
  645. }
  646. } // End of class