loginwebpage.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. utils::InitCASClient();
  93. // force CAS authentication
  94. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  95. break;
  96. case 'basic':
  97. case 'url':
  98. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  99. $this->add_header('HTTP/1.0 401 Unauthorized');
  100. // Note: displayed when the user will click on Cancel
  101. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  102. break;
  103. case 'external':
  104. case 'form':
  105. default: // In case the settings get messed up...
  106. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  107. $sAuthPwd = utils::ReadParam('suggest_pwd', '', true, 'raw_data');
  108. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  109. $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");
  110. $this->add("<div id=\"login\">\n");
  111. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  112. if ($bFailedLogin)
  113. {
  114. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  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 width=\"100%\">\n");
  122. $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");
  123. $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");
  124. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"submit\" value=\"".Dict::S('UI:Button:Login')."\" /></td></tr>\n");
  125. $this->add("</table>\n");
  126. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  127. $this->add("</form>\n");
  128. $this->add("</div>\n");
  129. break;
  130. }
  131. }
  132. public function DisplayChangePwdForm($bFailedLogin = false)
  133. {
  134. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  135. $sAuthPwd = utils::ReadParam('suggest_pwd', '', false, 'raw_data');
  136. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  137. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  138. $this->add_script(<<<EOF
  139. function GoBack()
  140. {
  141. window.history.back();
  142. }
  143. function DoCheckPwd()
  144. {
  145. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  146. {
  147. alert('$sInconsistenPwdMsg');
  148. return false;
  149. }
  150. return true;
  151. }
  152. EOF
  153. );
  154. $this->add("<div id=\"login-logo\"><a href=\"http://www.combodo.com/itop\"><img title=\"$sVersionShort\" src=\"../images/itop-logo.png\"></a></div>\n");
  155. $this->add("<div id=\"login\">\n");
  156. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  157. if ($bFailedLogin)
  158. {
  159. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  160. }
  161. $this->add("<form method=\"post\">\n");
  162. $this->add("<table width=\"100%\">\n");
  163. $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");
  164. $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");
  165. $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");
  166. $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");
  167. $this->add("</table>\n");
  168. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  169. $this->add("</form>\n");
  170. $this->add("</div>\n");
  171. }
  172. static function ResetSession()
  173. {
  174. if (isset($_SESSION['login_mode']))
  175. {
  176. $sPreviousLoginMode = $_SESSION['login_mode'];
  177. }
  178. else
  179. {
  180. $sPreviousLoginMode = '';
  181. }
  182. // Unset all of the session variables.
  183. $_SESSION = array();
  184. // If it's desired to kill the session, also delete the session cookie.
  185. // Note: This will destroy the session, and not just the session data!
  186. if (isset($_COOKIE[session_name()]))
  187. {
  188. setcookie(session_name(), '', time()-3600, '/');
  189. }
  190. // Finally, destroy the session.
  191. session_destroy();
  192. }
  193. static function SecureConnectionRequired()
  194. {
  195. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  196. }
  197. static function IsConnectionSecure()
  198. {
  199. $bSecured = false;
  200. if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off'))
  201. {
  202. $bSecured = true;
  203. }
  204. return $bSecured;
  205. }
  206. protected static function Login()
  207. {
  208. if (self::SecureConnectionRequired() && !self::IsConnectionSecure())
  209. {
  210. // Non secured URL... request for a secure connection
  211. throw new Exception('Secure connection required!');
  212. }
  213. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  214. if (isset($_SESSION['auth_user']))
  215. {
  216. //echo "User: ".$_SESSION['auth_user']."\n";
  217. // Already authentified
  218. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  219. return true;
  220. }
  221. else
  222. {
  223. $index = 0;
  224. $sLoginMode = '';
  225. $sAuthentication = 'internal';
  226. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  227. {
  228. $sLoginType = $aAllowedLoginTypes[$index];
  229. switch($sLoginType)
  230. {
  231. case 'cas':
  232. utils::InitCASClient();
  233. // check CAS authentication
  234. if (phpCAS::isAuthenticated())
  235. {
  236. // Check is a membership is required
  237. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  238. $bFound = false;
  239. if (!empty($sCASMemberships))
  240. {
  241. if (phpCAS::hasAttribute('memberOf'))
  242. {
  243. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  244. $aCASMemberships = array();
  245. $aTmp = explode(';', $sCASMemberships);
  246. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  247. foreach($aTmp as $sGroupName)
  248. {
  249. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  250. }
  251. $aMemberOf = phpCAS::getAttribute('memberOf');
  252. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  253. $aFilteredGroupNames = array();
  254. foreach($aMemberOf as $sGroupName)
  255. {
  256. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  257. $aFilteredGroupNames[] = $sGroupName;
  258. if (in_array($sGroupName, $aCASMemberships))
  259. {
  260. $bFound = true;
  261. break;
  262. }
  263. }
  264. if(!$bFound)
  265. {
  266. phpCAS :: log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  267. }
  268. }
  269. else
  270. {
  271. // Too bad, the user is not part of any of the group => not allowed
  272. phpCAS :: log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  273. }
  274. }
  275. else
  276. {
  277. // No membership required, anybody will pass
  278. $bFound = true;
  279. }
  280. if ($bFound)
  281. {
  282. $sAuthUser = phpCAS::getUser();
  283. $sAuthPwd = '';
  284. $sLoginMode = 'cas';
  285. $sAuthentication = 'external';
  286. }
  287. else
  288. {
  289. // The user is not part of the allowed groups, => log out
  290. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  291. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  292. if (empty($sCASLogoutUrl))
  293. {
  294. $sCASLogoutUrl = $sUrl;
  295. }
  296. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  297. }
  298. }
  299. break;
  300. case 'form':
  301. // iTop standard mode: form based authentication
  302. $sAuthUser = utils::ReadPostedParam('auth_user', '', 'raw_data');
  303. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', 'raw_data');
  304. if ($sAuthUser != '')
  305. {
  306. $sLoginMode = 'form';
  307. }
  308. break;
  309. case 'basic':
  310. // Standard PHP authentication method, works with Apache...
  311. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  312. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  313. {
  314. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  315. $sLoginMode = 'basic';
  316. }
  317. else if (isset($_SERVER['PHP_AUTH_USER']))
  318. {
  319. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  320. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  321. $sLoginMode = 'basic';
  322. }
  323. break;
  324. case 'external':
  325. // Web server supplied authentication
  326. $bExternalAuth = false;
  327. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  328. $sEval = '$bExternalAuth = isset('.$sExtAuthVar.');';
  329. eval($sEval);
  330. if ($bExternalAuth)
  331. {
  332. eval('$sAuthUser = '.$sExtAuthVar.';'); // Retrieve the value
  333. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  334. $sLoginMode = 'external';
  335. $sAuthentication = 'external';
  336. }
  337. break;
  338. case 'url':
  339. // Credentials passed directly in the url
  340. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  341. if ($sAuthUser != '')
  342. {
  343. $sAuthPwd = utils::ReadParam('auth_pwd', '', false, 'raw_data');
  344. $sLoginMode = 'url';
  345. }
  346. break;
  347. }
  348. $index++;
  349. }
  350. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  351. if ($sLoginMode == '')
  352. {
  353. // First connection
  354. $sDesiredLoginMode = utils::ReadParam('login_mode');
  355. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  356. {
  357. $sLoginMode = $sDesiredLoginMode;
  358. }
  359. else
  360. {
  361. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  362. }
  363. $oPage = new LoginWebPage();
  364. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  365. $oPage->output();
  366. exit;
  367. }
  368. else
  369. {
  370. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sAuthentication))
  371. {
  372. //echo "Check Credentials returned false for user $sAuthUser!";
  373. self::ResetSession();
  374. $oPage = new LoginWebPage();
  375. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  376. $oPage->output();
  377. exit;
  378. }
  379. else
  380. {
  381. // User is Ok, let's save it in the session and proceed with normal login
  382. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  383. if (MetaModel::GetConfig()->Get('log_usage'))
  384. {
  385. $oLog = new EventLoginUsage();
  386. $oLog->Set('userinfo', UserRights::GetUser());
  387. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  388. $oLog->Set('message', 'Successful login');
  389. $oLog->DBInsertNoReload();
  390. }
  391. $_SESSION['auth_user'] = $sAuthUser;
  392. $_SESSION['login_mode'] = $sLoginMode;
  393. }
  394. }
  395. }
  396. }
  397. /**
  398. * Check if the user is already authentified, if yes, then performs some additional validations:
  399. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  400. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  401. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  402. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  403. */
  404. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false)
  405. {
  406. $sMessage = ''; // In case we need to return a message to the calling web page
  407. $operation = utils::ReadParam('loginop', '');
  408. session_name(MetaModel::GetConfig()->Get('session_name'));
  409. session_start();
  410. if ($operation == 'logoff')
  411. {
  412. if (isset($_SESSION['login_mode']))
  413. {
  414. $sLoginMode = $_SESSION['login_mode'];
  415. }
  416. else
  417. {
  418. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  419. if (count($aAllowedLoginTypes) > 0)
  420. {
  421. $sLoginMode = $aAllowedLoginTypes[0];
  422. }
  423. else
  424. {
  425. $sLoginMode = 'form';
  426. }
  427. }
  428. self::ResetSession();
  429. $oPage = new LoginWebPage();
  430. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  431. $oPage->output();
  432. exit;
  433. }
  434. else if ($operation == 'change_pwd')
  435. {
  436. $sAuthUser = $_SESSION['auth_user'];
  437. UserRights::Login($sAuthUser); // Set the user's language
  438. $oPage = new LoginWebPage();
  439. $oPage->DisplayChangePwdForm();
  440. $oPage->output();
  441. exit;
  442. }
  443. if ($operation == 'do_change_pwd')
  444. {
  445. $sAuthUser = $_SESSION['auth_user'];
  446. UserRights::Login($sAuthUser); // Set the user's language
  447. $sOldPwd = utils::ReadPostedParam('old_pwd', 'raw_data');
  448. $sNewPwd = utils::ReadPostedParam('new_pwd', 'raw_data');
  449. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  450. {
  451. $oPage = new LoginWebPage();
  452. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  453. $oPage->output();
  454. }
  455. $sMessage = Dict::S('UI:Login:PasswordChanged');
  456. }
  457. self::Login();
  458. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  459. {
  460. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  461. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  462. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  463. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  464. $oP->output();
  465. exit;
  466. }
  467. elseif ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  468. {
  469. // No rights to be here, redirect to the portal
  470. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  471. }
  472. return $sMessage;
  473. }
  474. } // End of class
  475. ?>