loginwebpage.class.inc.php 24 KB

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