loginwebpage.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. // Copyright (C) 2010-2012 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-2012 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 $m_sLoginFailedMessage = '';
  31. public function __construct()
  32. {
  33. parent::__construct("iTop Login");
  34. $this->add_style(<<<EOF
  35. body {
  36. background: #eee;
  37. margin: 0;
  38. padding: 0;
  39. }
  40. #login-logo {
  41. margin-top: 150px;
  42. width: 300px;
  43. padding-left: 20px;
  44. padding-right: 20px;
  45. padding-top: 10px;
  46. padding-bottom: 10px;
  47. margin-left: auto;
  48. margin-right: auto;
  49. background: #f6f6f1;
  50. height: 54px;
  51. border-top: 1px solid #000;
  52. border-left: 1px solid #000;
  53. border-right: 1px solid #000;
  54. border-bottom: 0;
  55. text-align: center;
  56. }
  57. #login-logo img {
  58. border: 0;
  59. }
  60. #login {
  61. width: 300px;
  62. margin-left: auto;
  63. margin-right: auto;
  64. padding: 20px;
  65. background-color: #fff;
  66. border-bottom: 1px solid #000;
  67. border-left: 1px solid #000;
  68. border-right: 1px solid #000;
  69. border-top: 0;
  70. text-align: center;
  71. }
  72. #pwd, #user,#old_pwd, #new_pwd, #retype_new_pwd {
  73. width: 10em;
  74. }
  75. .center {
  76. text-align: center;
  77. }
  78. h1 {
  79. color: #1C94C4;
  80. font-size: 16pt;
  81. }
  82. .v-spacer {
  83. padding-top: 1em;
  84. }
  85. EOF
  86. );
  87. }
  88. public static function SetLoginFailedMessage($sMessage)
  89. {
  90. self::$m_sLoginFailedMessage = $sMessage;
  91. }
  92. public function DisplayLoginForm($sLoginType, $bFailedLogin = false)
  93. {
  94. switch($sLoginType)
  95. {
  96. case 'cas':
  97. utils::InitCASClient();
  98. // force CAS authentication
  99. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  100. break;
  101. case 'basic':
  102. case 'url':
  103. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  104. $this->add_header('HTTP/1.0 401 Unauthorized');
  105. // Note: displayed when the user will click on Cancel
  106. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  107. break;
  108. case 'external':
  109. case 'form':
  110. default: // In case the settings get messed up...
  111. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  112. $sAuthPwd = utils::ReadParam('suggest_pwd', '', true, 'raw_data');
  113. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  114. $sIconUrl = Utils::GetConfig()->Get('app_icon_url');
  115. $this->add("<div id=\"login-logo\"><a href=\"".htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8')."\"><img title=\"$sVersionShort\" src=\"../images/itop-logo-external.png\"></a></div>\n");
  116. $this->add("<div id=\"login\">\n");
  117. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  118. if ($bFailedLogin)
  119. {
  120. if (self::$m_sLoginFailedMessage != '')
  121. {
  122. $this->add("<p class=\"hilite\">".self::$m_sLoginFailedMessage."</p>\n");
  123. }
  124. else
  125. {
  126. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  127. }
  128. }
  129. else
  130. {
  131. $this->add("<p>".Dict::S('UI:Login:IdentifyYourself')."</p>\n");
  132. }
  133. $this->add("<form method=\"post\">\n");
  134. $this->add("<table width=\"100%\">\n");
  135. $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");
  136. $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");
  137. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"submit\" value=\"".Dict::S('UI:Button:Login')."\" /></td></tr>\n");
  138. $this->add("</table>\n");
  139. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  140. // Keep the OTHER parameters posted
  141. foreach($_POST as $sPostedKey => $sPostedValue)
  142. {
  143. if (!in_array($sPostedKey, array('auth_user', 'auth_pwd')))
  144. {
  145. $this->add("<input type=\"hidden\" name=\"".htmlentities($sPostedKey, ENT_QUOTES, 'UTF-8')."\" value=\"".htmlentities($sPostedValue, ENT_QUOTES, 'UTF-8')."\" />\n");
  146. }
  147. }
  148. $this->add("</form>\n");
  149. $this->add(Dict::S('UI:Login:About'));
  150. $this->add("</div>\n");
  151. break;
  152. }
  153. }
  154. public function DisplayChangePwdForm($bFailedLogin = false)
  155. {
  156. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  157. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  158. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  159. $this->add_script(<<<EOF
  160. function GoBack()
  161. {
  162. window.history.back();
  163. }
  164. function DoCheckPwd()
  165. {
  166. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  167. {
  168. alert('$sInconsistenPwdMsg');
  169. return false;
  170. }
  171. return true;
  172. }
  173. EOF
  174. );
  175. $sIconUrl = Utils::GetConfig()->Get('app_icon_url');
  176. $this->add("<div id=\"login-logo\"><a href=\"".htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8')."\"><img title=\"$sVersionShort\" src=\"../images/itop-logo.png\"></a></div>\n");
  177. $this->add("<div id=\"login\">\n");
  178. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  179. if ($bFailedLogin)
  180. {
  181. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  182. }
  183. $this->add("<form method=\"post\">\n");
  184. $this->add("<table width=\"100%\">\n");
  185. $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");
  186. $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");
  187. $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");
  188. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"button\" onClick=\"GoBack();\" value=\"".Dict::S('UI:Button:Cancel')."\" />&nbsp;&nbsp;<input type=\"submit\" onClick=\"return DoCheckPwd();\" value=\"".Dict::S('UI:Button:ChangePassword')."\" /></td></tr>\n");
  189. $this->add("</table>\n");
  190. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  191. $this->add("</form>\n");
  192. $this->add("</div>\n");
  193. }
  194. static function ResetSession()
  195. {
  196. if (isset($_SESSION['login_mode']))
  197. {
  198. $sPreviousLoginMode = $_SESSION['login_mode'];
  199. }
  200. else
  201. {
  202. $sPreviousLoginMode = '';
  203. }
  204. // Unset all of the session variables.
  205. unset($_SESSION['auth_user']);
  206. unset($_SESSION['login_mode']);
  207. // If it's desired to kill the session, also delete the session cookie.
  208. // Note: This will destroy the session, and not just the session data!
  209. }
  210. static function SecureConnectionRequired()
  211. {
  212. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  213. }
  214. protected static function Login()
  215. {
  216. if (self::SecureConnectionRequired() && !utils::IsConnectionSecure())
  217. {
  218. // Non secured URL... request for a secure connection
  219. throw new Exception('Secure connection required!');
  220. }
  221. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  222. if (isset($_SESSION['auth_user']))
  223. {
  224. //echo "User: ".$_SESSION['auth_user']."\n";
  225. // Already authentified
  226. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  227. return true;
  228. }
  229. else
  230. {
  231. $index = 0;
  232. $sLoginMode = '';
  233. $sAuthentication = 'internal';
  234. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  235. {
  236. $sLoginType = $aAllowedLoginTypes[$index];
  237. switch($sLoginType)
  238. {
  239. case 'cas':
  240. utils::InitCASClient();
  241. // check CAS authentication
  242. if (phpCAS::isAuthenticated())
  243. {
  244. $sAuthUser = phpCAS::getUser();
  245. $sAuthPwd = '';
  246. $sLoginMode = 'cas';
  247. $sAuthentication = 'external';
  248. }
  249. break;
  250. case 'form':
  251. // iTop standard mode: form based authentication
  252. $sAuthUser = utils::ReadPostedParam('auth_user', '', false, 'raw_data');
  253. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', false, 'raw_data');
  254. if ($sAuthUser != '')
  255. {
  256. $sLoginMode = 'form';
  257. }
  258. break;
  259. case 'basic':
  260. // Standard PHP authentication method, works with Apache...
  261. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  262. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  263. {
  264. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  265. $sLoginMode = 'basic';
  266. }
  267. else if (isset($_SERVER['PHP_AUTH_USER']))
  268. {
  269. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  270. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  271. $sLoginMode = 'basic';
  272. }
  273. break;
  274. case 'external':
  275. // Web server supplied authentication
  276. $bExternalAuth = false;
  277. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  278. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  279. if ($sAuthUser && (strlen($sAuthUser) > 0))
  280. {
  281. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  282. $sLoginMode = 'external';
  283. $sAuthentication = 'external';
  284. }
  285. break;
  286. case 'url':
  287. // Credentials passed directly in the url
  288. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  289. $sAuthPwd = utils::ReadParam('auth_pwd', null, false, 'raw_data');
  290. if (($sAuthUser != '') && ($sAuthPwd != null))
  291. {
  292. $sLoginMode = 'url';
  293. }
  294. break;
  295. }
  296. $index++;
  297. }
  298. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  299. if ($sLoginMode == '')
  300. {
  301. // First connection
  302. $sDesiredLoginMode = utils::ReadParam('login_mode');
  303. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  304. {
  305. $sLoginMode = $sDesiredLoginMode;
  306. }
  307. else
  308. {
  309. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  310. }
  311. $oPage = new LoginWebPage();
  312. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  313. $oPage->output();
  314. exit;
  315. }
  316. else
  317. {
  318. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sLoginMode, $sAuthentication))
  319. {
  320. //echo "Check Credentials returned false for user $sAuthUser!";
  321. self::ResetSession();
  322. $oPage = new LoginWebPage();
  323. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  324. $oPage->output();
  325. exit;
  326. }
  327. else
  328. {
  329. // User is Ok, let's save it in the session and proceed with normal login
  330. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  331. if (MetaModel::GetConfig()->Get('log_usage'))
  332. {
  333. $oLog = new EventLoginUsage();
  334. $oLog->Set('userinfo', UserRights::GetUser());
  335. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  336. $oLog->Set('message', 'Successful login');
  337. $oLog->DBInsertNoReload();
  338. }
  339. $_SESSION['auth_user'] = $sAuthUser;
  340. $_SESSION['login_mode'] = $sLoginMode;
  341. }
  342. }
  343. }
  344. }
  345. /**
  346. * Check if the user is already authentified, if yes, then performs some additional validations:
  347. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  348. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  349. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  350. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  351. */
  352. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false)
  353. {
  354. $sMessage = ''; // In case we need to return a message to the calling web page
  355. $operation = utils::ReadParam('loginop', '');
  356. if ($operation == 'logoff')
  357. {
  358. if (isset($_SESSION['login_mode']))
  359. {
  360. $sLoginMode = $_SESSION['login_mode'];
  361. }
  362. else
  363. {
  364. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  365. if (count($aAllowedLoginTypes) > 0)
  366. {
  367. $sLoginMode = $aAllowedLoginTypes[0];
  368. }
  369. else
  370. {
  371. $sLoginMode = 'form';
  372. }
  373. }
  374. self::ResetSession();
  375. $oPage = new LoginWebPage();
  376. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  377. $oPage->output();
  378. exit;
  379. }
  380. else if ($operation == 'change_pwd')
  381. {
  382. $sAuthUser = $_SESSION['auth_user'];
  383. UserRights::Login($sAuthUser); // Set the user's language
  384. $oPage = new LoginWebPage();
  385. $oPage->DisplayChangePwdForm();
  386. $oPage->output();
  387. exit;
  388. }
  389. if ($operation == 'do_change_pwd')
  390. {
  391. $sAuthUser = $_SESSION['auth_user'];
  392. UserRights::Login($sAuthUser); // Set the user's language
  393. $sOldPwd = utils::ReadPostedParam('old_pwd', '', false, 'raw_data');
  394. $sNewPwd = utils::ReadPostedParam('new_pwd', '', false, 'raw_data');
  395. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  396. {
  397. $oPage = new LoginWebPage();
  398. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  399. $oPage->output();
  400. }
  401. $sMessage = Dict::S('UI:Login:PasswordChanged');
  402. }
  403. self::Login();
  404. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  405. {
  406. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  407. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  408. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  409. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  410. $oP->output();
  411. exit;
  412. }
  413. elseif ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  414. {
  415. // No rights to be here, redirect to the portal
  416. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  417. }
  418. return $sMessage;
  419. }
  420. } // End of class
  421. ?>