loginwebpage.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class LoginWebPage
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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. public function __construct()
  31. {
  32. parent::__construct("iTop Login");
  33. $this->add_style(<<<EOF
  34. body {
  35. background: #eee;
  36. margin: 0;
  37. padding: 0;
  38. }
  39. #login-logo {
  40. margin-top: 150px;
  41. width: 300px;
  42. padding-left: 20px;
  43. padding-right: 20px;
  44. padding-top: 10px;
  45. padding-bottom: 10px;
  46. margin-left: auto;
  47. margin-right: auto;
  48. background: #f6f6f1;
  49. height: 54px;
  50. border-top: 1px solid #000;
  51. border-left: 1px solid #000;
  52. border-right: 1px solid #000;
  53. border-bottom: 0;
  54. text-align: center;
  55. }
  56. #login-logo img {
  57. border: 0;
  58. }
  59. #login {
  60. width: 300px;
  61. margin-left: auto;
  62. margin-right: auto;
  63. padding: 20px;
  64. background-color: #fff;
  65. border-bottom: 1px solid #000;
  66. border-left: 1px solid #000;
  67. border-right: 1px solid #000;
  68. border-top: 0;
  69. text-align: center;
  70. }
  71. #pwd, #user,#old_pwd, #new_pwd, #retype_new_pwd {
  72. width: 10em;
  73. }
  74. .center {
  75. text-align: center;
  76. }
  77. h1 {
  78. color: #1C94C4;
  79. font-size: 16pt;
  80. }
  81. .v-spacer {
  82. padding-top: 1em;
  83. }
  84. EOF
  85. );
  86. }
  87. public function DisplayLoginForm($sLoginType, $bFailedLogin = false)
  88. {
  89. switch($sLoginType)
  90. {
  91. case 'cas':
  92. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  93. include_once($sCASIncludePath.'/CAS.php');
  94. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  95. if ($bCASDebug)
  96. {
  97. phpCAS::setDebug(APPROOT.'/error.log');
  98. }
  99. // Initialize phpCAS
  100. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  101. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  102. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  103. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  104. phpCAS::client(CAS_VERSION_2_0, $sCASHost, $iCASPort, $sCASContext);
  105. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  106. if (empty($sCASCACertPath))
  107. {
  108. // If no certificate authority is provided, do not attempt to validate
  109. // the server's certificate
  110. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  111. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  112. phpCAS::setNoCasServerValidation();
  113. }
  114. else
  115. {
  116. phpCAS::setCasServerCACert($sCASCACertPath);
  117. }
  118. // force CAS authentication
  119. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  120. break;
  121. case 'basic':
  122. case 'url':
  123. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  124. $this->add_header('HTTP/1.0 401 Unauthorized');
  125. // Note: displayed when the user will click on Cancel
  126. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  127. break;
  128. case 'external':
  129. case 'form':
  130. default: // In case the settings get messed up...
  131. $sAuthUser = utils::ReadParam('auth_user', '');
  132. $sAuthPwd = utils::ReadParam('suggest_pwd', '');
  133. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  134. $this->add("<div id=\"login-logo\"><a href=\"http://www.combodo.com/itop\"><img title=\"$sVersionShort\" src=\"../images/itop-logo-external.png\"></a></div>\n");
  135. $this->add("<div id=\"login\">\n");
  136. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  137. if ($bFailedLogin)
  138. {
  139. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  140. }
  141. else
  142. {
  143. $this->add("<p>".Dict::S('UI:Login:IdentifyYourself')."</p>\n");
  144. }
  145. $this->add("<form method=\"post\">\n");
  146. $this->add("<table width=\"100%\">\n");
  147. $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=\"$sAuthUser\" /></td></tr>\n");
  148. $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=\"$sAuthPwd\" /></td></tr>\n");
  149. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"submit\" value=\"".Dict::S('UI:Button:Login')."\" /></td></tr>\n");
  150. $this->add("</table>\n");
  151. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  152. $this->add("</form>\n");
  153. $this->add("</div>\n");
  154. break;
  155. }
  156. }
  157. public function DisplayChangePwdForm($bFailedLogin = false)
  158. {
  159. $sAuthUser = utils::ReadParam('auth_user', '');
  160. $sAuthPwd = utils::ReadParam('suggest_pwd', '');
  161. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  162. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  163. $this->add_script(<<<EOF
  164. function GoBack()
  165. {
  166. window.history.back();
  167. }
  168. function DoCheckPwd()
  169. {
  170. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  171. {
  172. alert('$sInconsistenPwdMsg');
  173. return false;
  174. }
  175. return true;
  176. }
  177. EOF
  178. );
  179. $this->add("<div id=\"login-logo\"><a href=\"http://www.combodo.com/itop\"><img title=\"$sVersionShort\" src=\"../images/itop-logo.png\"></a></div>\n");
  180. $this->add("<div id=\"login\">\n");
  181. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  182. if ($bFailedLogin)
  183. {
  184. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  185. }
  186. $this->add("<form method=\"post\">\n");
  187. $this->add("<table width=\"100%\">\n");
  188. $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");
  189. $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");
  190. $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");
  191. $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");
  192. $this->add("</table>\n");
  193. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  194. $this->add("</form>\n");
  195. $this->add("</div>\n");
  196. }
  197. static function ResetSession()
  198. {
  199. if (isset($_SESSION['login_mode']))
  200. {
  201. $sPreviousLoginMode = $_SESSION['login_mode'];
  202. }
  203. else
  204. {
  205. $sPreviousLoginMode = '';
  206. }
  207. // Unset all of the session variables.
  208. $_SESSION = array();
  209. // If it's desired to kill the session, also delete the session cookie.
  210. // Note: This will destroy the session, and not just the session data!
  211. if (isset($_COOKIE[session_name()]))
  212. {
  213. setcookie(session_name(), '', time()-3600, '/');
  214. }
  215. // Finally, destroy the session.
  216. session_destroy();
  217. }
  218. static function SecureConnectionRequired()
  219. {
  220. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  221. }
  222. static function IsConnectionSecure()
  223. {
  224. $bSecured = false;
  225. if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off'))
  226. {
  227. $bSecured = true;
  228. }
  229. return $bSecured;
  230. }
  231. protected static function Login()
  232. {
  233. if (self::SecureConnectionRequired() && !self::IsConnectionSecure())
  234. {
  235. // Non secured URL... redirect to a secured one
  236. $sUrl = Utils::GetAbsoluteUrl(true /* query string */, true /* force HTTPS */);
  237. header("Location: $sUrl");
  238. exit;
  239. }
  240. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  241. if (isset($_SESSION['auth_user']))
  242. {
  243. //echo "User: ".$_SESSION['auth_user']."\n";
  244. // Already authentified
  245. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  246. return true;
  247. }
  248. else
  249. {
  250. $index = 0;
  251. $sLoginMode = '';
  252. $sAuthentication = 'internal';
  253. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  254. {
  255. $sLoginType = $aAllowedLoginTypes[$index];
  256. switch($sLoginType)
  257. {
  258. case 'cas':
  259. $sCASIncludePath = MetaModel::GetConfig()->Get('cas_include_path');
  260. include_once($sCASIncludePath.'/CAS.php');
  261. $bCASDebug = MetaModel::GetConfig()->Get('cas_debug');
  262. if ($bCASDebug)
  263. {
  264. phpCAS::setDebug(APPROOT.'/error.log');
  265. }
  266. // Initialize phpCAS
  267. $sCASVersion = MetaModel::GetConfig()->Get('cas_version');
  268. $sCASHost = MetaModel::GetConfig()->Get('cas_host');
  269. $iCASPort = MetaModel::GetConfig()->Get('cas_port');
  270. $sCASContext = MetaModel::GetConfig()->Get('cas_context');
  271. phpCAS::client(CAS_VERSION_2_0, $sCASHost, $iCASPort, $sCASContext);
  272. $sCASCACertPath = MetaModel::GetConfig()->Get('cas_server_ca_cert_path');
  273. if (empty($sCASCACertPath))
  274. {
  275. // If no certificate authority is provided, do not attempt to validate
  276. // the server's certificate
  277. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION.
  278. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL!
  279. phpCAS::setNoCasServerValidation();
  280. }
  281. else
  282. {
  283. phpCAS::setCasServerCACert($sCASCACertPath);
  284. }
  285. // check CAS authentication
  286. if (phpCAS::isAuthenticated())
  287. {
  288. $sAuthUser = phpCAS::getUser();
  289. $sAuthPwd = '';
  290. $sLoginMode = 'cas';
  291. $sAuthentication = 'external';
  292. }
  293. break;
  294. case 'form':
  295. // iTop standard mode: form based authentication
  296. $sAuthUser = utils::ReadPostedParam('auth_user', '');
  297. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '');
  298. if ($sAuthUser != '')
  299. {
  300. $sLoginMode = 'form';
  301. }
  302. break;
  303. case 'basic':
  304. // Standard PHP authentication method, works with Apache...
  305. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  306. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  307. {
  308. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  309. $sLoginMode = 'basic';
  310. }
  311. else if (isset($_SERVER['PHP_AUTH_USER']))
  312. {
  313. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  314. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  315. $sLoginMode = 'basic';
  316. }
  317. break;
  318. case 'external':
  319. // Web server supplied authentication
  320. $bExternalAuth = false;
  321. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  322. $sEval = '$bExternalAuth = isset('.$sExtAuthVar.');';
  323. eval($sEval);
  324. if ($bExternalAuth)
  325. {
  326. eval('$sAuthUser = '.$sExtAuthVar.';'); // Retrieve the value
  327. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  328. $sLoginMode = 'external';
  329. $sAuthentication = 'external';
  330. }
  331. break;
  332. case 'url':
  333. // Credentials passed directly in the url
  334. $sAuthUser = utils::ReadParam('auth_user', '');
  335. if ($sAuthUser != '')
  336. {
  337. $sAuthPwd = utils::ReadParam('auth_pwd', '');
  338. $sLoginMode = 'url';
  339. }
  340. break;
  341. }
  342. $index++;
  343. }
  344. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  345. if ($sLoginMode == '')
  346. {
  347. // First connection
  348. $sDesiredLoginMode = utils::ReadParam('login_mode');
  349. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  350. {
  351. $sLoginMode = $sDesiredLoginMode;
  352. }
  353. else
  354. {
  355. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  356. }
  357. $oPage = new LoginWebPage();
  358. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  359. $oPage->output();
  360. exit;
  361. }
  362. else
  363. {
  364. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sAuthentication))
  365. {
  366. //echo "Check Credentials returned false for user $sAuthUser!";
  367. self::ResetSession();
  368. $oPage = new LoginWebPage();
  369. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  370. $oPage->output();
  371. exit;
  372. }
  373. else
  374. {
  375. // User is Ok, let's save it in the session and proceed with normal login
  376. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  377. if (MetaModel::GetConfig()->Get('log_usage'))
  378. {
  379. $oLog = new EventLoginUsage();
  380. $oLog->Set('userinfo', UserRights::GetUser());
  381. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  382. $oLog->Set('message', 'Successful login');
  383. $oLog->DBInsertNoReload();
  384. }
  385. $_SESSION['auth_user'] = $sAuthUser;
  386. $_SESSION['login_mode'] = $sLoginMode;
  387. }
  388. }
  389. }
  390. }
  391. /**
  392. * Check if the user is already authentified, if yes, then performs some additional validations:
  393. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  394. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  395. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  396. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  397. */
  398. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false)
  399. {
  400. $sMessage = ''; // In case we need to return a message to the calling web page
  401. $operation = utils::ReadParam('loginop', '');
  402. session_name(MetaModel::GetConfig()->Get('session_name'));
  403. session_start();
  404. if ($operation == 'logoff')
  405. {
  406. if (isset($_SESSION['login_mode']))
  407. {
  408. $sLoginMode = $_SESSION['login_mode'];
  409. }
  410. else
  411. {
  412. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  413. if (count($aAllowedLoginTypes) > 0)
  414. {
  415. $sLoginMode = $aAllowedLoginTypes[0];
  416. }
  417. else
  418. {
  419. $sLoginMode = 'form';
  420. }
  421. }
  422. self::ResetSession();
  423. $oPage = new LoginWebPage();
  424. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  425. $oPage->output();
  426. exit;
  427. }
  428. else if ($operation == 'change_pwd')
  429. {
  430. $sAuthUser = $_SESSION['auth_user'];
  431. UserRights::Login($sAuthUser); // Set the user's language
  432. $oPage = new LoginWebPage();
  433. $oPage->DisplayChangePwdForm();
  434. $oPage->output();
  435. exit;
  436. }
  437. if ($operation == 'do_change_pwd')
  438. {
  439. $sAuthUser = $_SESSION['auth_user'];
  440. UserRights::Login($sAuthUser); // Set the user's language
  441. $sOldPwd = utils::ReadPostedParam('old_pwd');
  442. $sNewPwd = utils::ReadPostedParam('new_pwd');
  443. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  444. {
  445. $oPage = new LoginWebPage();
  446. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  447. $oPage->output();
  448. }
  449. $sMessage = Dict::S('UI:Login:PasswordChanged');
  450. }
  451. self::Login();
  452. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  453. {
  454. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  455. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  456. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  457. $oP->p("<a href=\"../pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  458. $oP->output();
  459. exit;
  460. }
  461. elseif ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  462. {
  463. // No rights to be here, redirect to the portal
  464. header('Location: ../portal/index.php');
  465. }
  466. return $sMessage;
  467. }
  468. } // End of class
  469. ?>