loginwebpage.class.inc.php 15 KB

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