Debian Codegraph @

templates/login.php

raw
1 <?php
2
3 namespace LAM\LOGIN;
4
5 use htmlLabel;
6 use htmlResponsiveSelect;
7 use LAM\ENV\LAMLicenseValidator;
8 use LAM\ENV\LicenseWarningMailer;
9 use LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
10 use LAMConfig;
11 use LAMCfgMain;
12 use htmlSpacer;
13 use htmlOutputText;
14 use htmlSelect;
15 use htmlInputField;
16 use htmlGroup;
17 use htmlInputCheckbox;
18 use htmlButton;
19 use htmlStatusMessage;
20 use LAMException;
21 use Ldap;
22 use htmlResponsiveRow;
23 use htmlDiv;
24 use ServerProfilePersistenceManager;
25
26 /*
27
28 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
29 Copyright (C) 2003 - 2006 Michael Duergner
30 2005 - 2026 Roland Gruber
31
32 This program is free software; you can redistribute it and/or modify
33 it under the terms of the GNU General Public License as published by
34 the Free Software Foundation; either version 2 of the License, or
35 (at your option) any later version.
36
37 This program is distributed in the hope that it will be useful,
38 but WITHOUT ANY WARRANTY; without even the implied warranty of
39 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 GNU General Public License for more details.
41
42 You should have received a copy of the GNU General Public License
43 along with this program; if not, write to the Free Software
44 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
45
46 */
47
48 /**
49 * Login form of LDAP Account Manager.
50 *
51 * @author Michael Duergner
52 * @author Roland Gruber
53 * @package main
54 */
55
56 /** status messages */
57 include_once(__DIR__ . "/../lib/status.inc");
58
59 /** check environment */
60 include __DIR__ . '/../lib/checkEnvironment.inc';
61
62 /** security functions */
63 include_once(__DIR__ . "/../lib/security.inc");
64 /** self-service functions */
65 include_once(__DIR__ . "/../lib/selfService.inc");
66 /** access to configuration options */
67 include_once(__DIR__ . "/../lib/config.inc");
68
69 $cfgMain = new LAMCfgMain();
70
71 // check if main config password is set
72 if (!$cfgMain->hasPasswordSet()) {
73 metaRefresh('setInitialPassword.php');
74 die();
75 }
76
77 $licenseValidator = null;
78 if (isLAMProVersion()) {
79 include_once(__DIR__ . "/../lib/env.inc");
80 $licenseValidator = new LAMLicenseValidator();
81 $licenseValidator->validateAndRedirect('config/mainlogin.php?invalidLicense=1', 'config/mainlogin.php?invalidLicense=2');
82 }
83
84 // set session save path
85 if (isFileBasedSession()) {
86 session_save_path(__DIR__ . '/../sess');
87 }
88
89 // start empty session and change ID for security reasons
90 lam_start_session();
91 session_destroy();
92 lam_start_session();
93 session_regenerate_id(true);
94
95 $serverProfilePersistenceManager = new ServerProfilePersistenceManager();
96 $profiles = [];
97 try {
98 $profiles = $serverProfilePersistenceManager->getProfiles();
99 }
100 catch (LAMException $e) {
101 logNewMessage(LOG_ERR, 'Unable to read server profiles: ' . $e->getTitle());
102 }
103
104 // save last selected login profile
105 if (isset($_GET['useProfile'])) {
106 if (in_array($_GET['useProfile'], $profiles)) {
107 $cookieOptions = lamDefaultCookieOptions();
108 $cookieOptions['expires'] = time() + (60 * 60 * 24 * 365);
109 setcookie("lam_default_profile", (string) $_GET['useProfile'], $cookieOptions);
110 }
111 else {
112 unset($_GET['useProfile']);
113 }
114 }
115
116 // save last selected language
117 if (isset($_POST['language'])) {
118 $cookieOptions = lamDefaultCookieOptions();
119 $cookieOptions['expires'] = time() + (60 * 60 * 24 * 365);
120 setcookie('lam_last_language', htmlspecialchars((string) $_POST['language']), $cookieOptions);
121 }
122
123 $_SESSION["cfgMain"] = $cfgMain;
124 setSSLCaCert();
125
126 $default_Profile = $cfgMain->default;
127 if (isset($_COOKIE["lam_default_profile"]) && in_array($_COOKIE["lam_default_profile"], $profiles)) {
128 $default_Profile = $_COOKIE["lam_default_profile"];
129 }
130
131 $error_message = null;
132
133 try {
134 // Reload login page after a profile change
135 if (isset($_GET['useProfile']) && in_array($_GET['useProfile'], $profiles)) {
136 logNewMessage(LOG_DEBUG, "Change server profile to " . $_GET['useProfile']);
137 $_SESSION['config'] = $serverProfilePersistenceManager->loadProfile($_GET['useProfile']);
138 } // Load login page
139 elseif (!empty($default_Profile) && in_array($default_Profile, $profiles)) {
140 $_SESSION["config"] = $serverProfilePersistenceManager->loadProfile($default_Profile);
141 } // use first profile as fallback
142 elseif (count($profiles) > 0) {
143 $_SESSION["config"] = $serverProfilePersistenceManager->loadProfile($profiles[0]);
144 }
145 else {
146 $_SESSION["config"] = null;
147 }
148 }
149 catch (LAMException $e) {
150 $error_message = $e->getTitle();
151 }
152
153 if (!isset($cfgMain->default) || !in_array($cfgMain->default, $profiles)) {
154 $error_message = _('No default profile set. Please set it in the server profile configuration.');
155 }
156
157 $possibleLanguages = getLanguages();
158 $encoding = 'UTF-8';
159 if (isset($_COOKIE['lam_last_language'])) {
160 foreach ($possibleLanguages as $lang) {
161 if (str_starts_with((string) $_COOKIE['lam_last_language'], $lang->code)) {
162 $_SESSION['language'] = $lang->code;
163 $encoding = $lang->encoding;
164 break;
165 }
166 }
167 }
168 elseif (!empty($_SESSION["config"])) {
169 $defaultLang = $_SESSION["config"]->get_defaultLanguage();
170 foreach ($possibleLanguages as $lang) {
171 if (str_starts_with($defaultLang, $lang->code)) {
172 $_SESSION['language'] = $lang->code;
173 $encoding = $lang->encoding;
174 break;
175 }
176 }
177 }
178 else {
179 $_SESSION['language'] = 'en_GB.utf8';
180 }
181 if (isset($_POST['language'])) {
182 foreach ($possibleLanguages as $lang) {
183 if (str_starts_with((string) $_POST['language'], $lang->code)) {
184 $_SESSION['language'] = $lang->code;
185 $encoding = $lang->encoding;
186 break;
187 }
188 }
189 }
190
191 $_SESSION['header'] = "<!DOCTYPE html>\n\n";
192 $_SESSION['header'] .= "<html>\n<head>\n";
193 $_SESSION['header'] .= "<meta name=\"robots\" content=\"noindex, nofollow\">\n";
194 $_SESSION['header'] .= "<meta http-equiv=\"content-type\" content=\"text/html; charset=" . $encoding . "\">\n";
195 $_SESSION['header'] .= "<meta http-equiv=\"pragma\" content=\"no-cache\">\n <meta http-equiv=\"cache-control\" content=\"no-cache\">";
196 $manifestBaseUrl = getCallingURL();
197 if (str_contains($manifestBaseUrl, '/templates/login.php')) {
198 $manifestBaseUrl = substr($manifestBaseUrl, 0, strpos($manifestBaseUrl, '/templates/login.php'));
199 $urlMatches = [];
200 if (preg_match('/^http(s)?:\\/\\/[^\\/]+(\\/.*)$/m', $manifestBaseUrl, $urlMatches)) {
201 $manifestBaseUrl = htmlspecialchars($urlMatches[2]);
202 $_SESSION['header'] .= '<link rel="manifest" href="' . $manifestBaseUrl . '/templates/manifest.php" crossorigin="use-credentials">';
203 }
204 }
205
206 setlanguage(); // setting correct language
207
208 /**
209 * Displays the login window.
210 *
211 * @param LAMLicenseValidator|null $licenseValidator license validator
212 * @param string|null $error_message error message to display
213 * @param string|null $errorDetails error details
214 * @param string|null $extraMessage extra message that is shown as info
215 * @throws LAMException error rendering login page
216 */
217 function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $error_message, ?string $errorDetails = null, ?string $extraMessage = null): void {
218 $config_object = $_SESSION['config'] ?? null;
219 $cfgMain = $_SESSION["cfgMain"];
220 if (!($cfgMain instanceof LAMCfgMain)) {
221 die();
222 }
223 logNewMessage(LOG_DEBUG, "Display login page");
224 // generate 256 bit key and initialization vector for user/passwd-encryption
225 $key = openssl_random_pseudo_bytes(32);
226 $iv = openssl_random_pseudo_bytes(16);
227 // save both in cookie
228 $cookieOptions = lamDefaultCookieOptions();
229 $cookieOptions['expires'] = 0;
230 setcookie("Key", base64_encode($key), $cookieOptions);
231 setcookie("IV", base64_encode($iv), $cookieOptions);
232
233 $serverProfilePersistenceManager = new ServerProfilePersistenceManager();
234 $profiles = $serverProfilePersistenceManager->getProfiles();
235
236 echo $_SESSION["header"];
237 printHeaderContents('LDAP Account Manager', '..');
238 ?>
239 </head>
240 <body>
241 <?php
242 // include all JavaScript files
243 printJsIncludes('..');
244
245 if (isLAMProVersion() && ($licenseValidator !== null) && $licenseValidator->isEvaluationLicense()) {
246 StatusMessage('INFO', _('Evaluation Licence'));
247 }
248 displayLoginHeader();
249
250 if (!empty($config_object)) {
251 // check TLS
252 $useTLS = $config_object->getUseTLS();
253 if (isset($useTLS) && ($useTLS == "yes") && !function_exists('ldap_start_tls')) {
254 StatusMessage("ERROR", "Your PHP installation does not support TLS encryption!");
255 echo "<br>";
256 }
257 }
258 elseif ($error_message !== null) {
259 StatusMessage("ERROR", $error_message);
260 }
261 else {
262 StatusMessage('WARN', _('Please enter the configuration and create a server profile.'));
263 }
264 // check if session expired
265 if (isset($_GET['expired'])) {
266 StatusMessage("ERROR", _("Your session expired, please log in again."));
267 echo "<br>";
268 }
269 if (!empty($config_object)) {
270 ?>
271 <br><br><br>
272 <div class="centeredTable">
273 <div class="roundedShadowBox limitWidth" style="position:relative; z-index:5;">
274 <table border="0" rules="none" bgcolor="white">
275 <tr>
276 <td style="border-style:none">
277 <form action="login.php" method="post">
278 <?php
279 $row = new htmlResponsiveRow();
280 // user name
281 $row->addLabel(new htmlLabel('username', _("User name")));
282 if ($config_object->getLoginMethod() == LAMConfig::LOGIN_LIST) {
283 $admins = $config_object->get_Admins();
284 $adminList = [];
285 foreach ($admins as $admin) {
286 $text = explode(",", (string) $admin);
287 $text = explode("=", $text[0]);
288 if (isset($text[1])) {
289 $adminList[$text[1]] = $admin;
290 }
291 else {
292 $adminList[$text[0]] = $admin;
293 }
294 }
295 $selectedAdmin = [];
296 if (isset($_POST['username']) && in_array($_POST['username'], $adminList)) {
297 $selectedAdmin = [$_POST['username']];
298 }
299 $userSelect = new htmlSelect('username', $adminList, $selectedAdmin);
300 $userSelect->setHasDescriptiveElements(true);
301 $userSelect->setTransformSingleSelect(false);
302 if (empty($_COOKIE['lam_login_name'])) {
303 $userSelect->setCSSClasses(['lam-initial-focus']);
304 }
305 $row->addField(new htmlDiv(null, $userSelect));
306 }
307 elseif ($config_object->getHttpAuthentication() == 'true') {
308 $httpAuth = new htmlDiv(null, new htmlOutputText($_SERVER['PHP_AUTH_USER'] . '&nbsp;', false));
309 $httpAuth->setCSSClasses(['text-left', 'margin3']);
310 $row->addField($httpAuth);
311 }
312 else {
313 $user = '';
314 if (isset($_COOKIE["lam_login_name"])) {
315 $user = (string) $_COOKIE["lam_login_name"];
316 }
317 $userNameInput = new htmlInputField('username', $user);
318 if (empty($_COOKIE['lam_login_name'])) {
319 $userNameInput->setCSSClasses(['lam-initial-focus']);
320 }
321 $userInput = new htmlDiv(null, $userNameInput);
322 $row->addField($userInput);
323 }
324 // password
325 $row->addLabel(new htmlLabel('passwd', _("Password")));
326 if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($config_object->getHttpAuthentication() == 'true')) {
327 $passwordInputFake = new htmlDiv(null, new htmlOutputText('**********'));
328 $passwordInputFake->setCSSClasses(['text-left', 'margin3']);
329 $row->addField($passwordInputFake);
330 }
331 else {
332 $passwordInput = new htmlInputField('passwd');
333 $passwordInput->setIsPassword(true);
334 if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !empty($_COOKIE['lam_login_name'])) {
335 $passwordInput->setCSSClasses(['lam-initial-focus']);
336 }
337 $row->addField($passwordInput);
338 }
339 // language
340 $row->addLabel(new htmlLabel('language', _("Language")));
341 $possibleLanguages = getLanguages();
342 $languageList = [];
343 $defaultLanguage = [];
344 foreach ($possibleLanguages as $lang) {
345 $languageList[$lang->description] = $lang->code;
346 if (str_starts_with(trim((string) $_SESSION["language"]), $lang->code)) {
347 $defaultLanguage[] = $lang->code;
348 }
349 }
350 $languageSelect = new htmlSelect('language', $languageList, $defaultLanguage);
351 $languageSelect->setHasDescriptiveElements(true);
352 $row->addField($languageSelect);
353 // remember login user
354 if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($config_object->getHttpAuthentication() != 'true')) {
355 $row->add(new htmlOutputText('&nbsp;', false), 0, 6, 6);
356 $rememberGroup = new htmlGroup();
357 $doRemember = false;
358 if (isset($_COOKIE["lam_login_name"])) {
359 $doRemember = true;
360 }
361 $rememberGroup->addElement(new htmlInputCheckbox('rememberLogin', $doRemember));
362 $rememberGroup->addElement(new htmlSpacer('1px', null));
363 $rememberGroup->addElement(new htmlOutputText(_('Remember user name')));
364 $rememberDiv = new htmlDiv(null, $rememberGroup);
365 $rememberDiv->setCSSClasses(['text-left', 'margin3']);
366 $row->add($rememberDiv, 12, 6, 6);
367 }
368 // login button
369 $row->add(new htmlSpacer(null, '20px'));
370 $loginButton = new htmlButton('checklogin', _("Login"));
371 $loginButton->setCSSClasses(['lam-primary']);
372 $row->add($loginButton);
373
374 parseHtml(null, $row, [], false, 'user');
375 ?>
376 </form>
377 </td>
378 <td class="loginRightBox hide-for-small" style="border-style:none">
379 </td>
380 </tr>
381 <tr>
382 <td colspan="2" style="border-style:none;">
383 <?php
384 $row = new htmlResponsiveRow();
385 // error message
386 if (!empty($error_message)) {
387 $row->add(new htmlSpacer(null, '5px'));
388 $message = new htmlStatusMessage('ERROR', $error_message, $errorDetails);
389 $row->add($message);
390 }
391 if (!empty($extraMessage)) {
392 $extraMessage = new htmlStatusMessage('INFO', $extraMessage);
393 $row->add($extraMessage);
394 }
395 parseHtml(null, $row, [], false, 'user');
396 ?>
397 <hr class="margin20">
398 </td>
399 </tr>
400 <tr>
401 <td style="border-style:none;">
402 <form action="login.php" method="post">
403 <?php
404 $row = new htmlResponsiveRow();
405 $row->addLabel(new htmlOutputText(_("LDAP server")));
406 $serverUrl = new htmlOutputText($config_object->getServerDisplayNameGUI());
407 $serverUrlDiv = new htmlDiv(null, $serverUrl);
408 $serverUrlDiv->setCSSClasses(['text-left', 'margin3']);
409 $row->addField($serverUrlDiv);
410 $profileSelect = new htmlResponsiveSelect('profile', $profiles, [$_SESSION['config']->getName()], _("Server profile"));
411 $profileSelect->setOnchangeEvent('loginProfileChanged(this)');
412 $row->add($profileSelect);
413
414 parseHtml(null, $row, [], true, 'user');
415 ?>
416 </form>
417 </td>
418 <td class="loginRightBox hide-for-small" style="border-style:none">
419 </td>
420 </tr>
421 </table>
422 </div>
423 </div>
424 <?php
425 }
426 ?>
427 <br><br>
428 <?php
429 if (isLAMProVersion() && ($licenseValidator !== null)
430 && ($licenseValidator->getLicense() !== null) && $licenseValidator->isExpiringSoon()) {
431 $expirationDate = $licenseValidator->getLicense()->getExpirationDate()->format('Y-m-d');
432 $expirationTimeStamp = $licenseValidator->getLicense()->getExpirationDate()->getTimestamp();
433 if ($cfgMain->showLicenseWarningOnScreen()) {
434 $licenseMessage = sprintf(_('Your licence expires on %s. You need to purchase a new licence to be able to use LAM Pro after this date.'), $expirationDate);
435 StatusMessage('WARN', $licenseMessage);
436 }
437 if ($cfgMain->sendLicenseWarningByEmail() && !$cfgMain->wasLicenseWarningSent($expirationTimeStamp)) {
438 $cfgMain->licenseEmailDateSent = (string) $expirationTimeStamp;
439 $cfgMain->save();
440 $mailer = new LicenseWarningMailer($cfgMain);
441 $mailer->sendMail($expirationDate);
442 }
443 }
444 ?>
445 <br><br>
446 </body>
447 </html>
448 <?php
449 }
450
451 /**
452 * Displays the header on the login page.
453 */
454 function displayLoginHeader(): void {
455 ?>
456 <div id="lam-topnav" class="lam-header">
457 <div class="lam-header-left lam-menu-stay">
458 <a href="https://www.ldap-account-manager.org/" target="new_window">
459 <img class="align-middle" width="24" height="24" alt="help" src="../graphics/logo.svg">
460 <span class="hide-on-mobile">
461 <?php
462 echo getLAMVersionText();
463 ?>
464 </span>
465 </a>
466 <?php
467 if (!isLAMProVersion()) {
468 ?>
469 <span class="hide-on-mobile lam-margin-small">
470 &nbsp;&nbsp;&nbsp;&nbsp;
471 <a href="http://www.ldap-account-manager.org/lamcms/lamPro"><?php echo _("Want more features? Get LAM Pro!"); ?></a>
472 </span>
473 <?php
474 }
475 ?>
476 </div>
477 <a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon"
478 onclick="window.lam.topmenu.toggle();">
479 <img class="align-middle" width="16" height="16" alt="menu" src="../graphics/menu.svg">
480 <span class="padding0"></span>
481 </a>
482 <div class="lam-header-right lam-header-menublock">
483 <a class="lam-menu-entry" href="config/index.php" target="_top">
484 <span class="padding0"><?php echo _("LAM configuration") ?></span>
485 </a>
486 <?php
487 if (is_dir(__DIR__ . '/../docs/manual')) {
488 ?>
489 <a class="lam-menu-entry" target="_blank" href="../docs/manual/index.html">
490 <span class="padding0"><?php echo _("Help") ?></span>
491 </a>
492 <?php
493 }
494 ?>
495 </div>
496
497 </div>
498 <br>
499 <?php
500 }
501
502 // checking if the submitted username/password is correct.
503 if (isset($_POST['checklogin'])) {
504 include_once(__DIR__ . "/../lib/ldap.inc"); // Include ldap.php which provides Ldap class
505
506 $_SESSION['ldap'] = new Ldap($_SESSION['config']); // Create new Ldap object
507
508 $clientSource = $_SERVER['REMOTE_ADDR'];
509 if (isset($_SERVER['REMOTE_HOST'])) {
510 $clientSource .= '/' . $_SERVER['REMOTE_HOST'];
511 }
512 if (($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($_SESSION['config']->getHttpAuthentication() == 'true')) {
513 $username = $_SERVER['PHP_AUTH_USER'];
514 $password = $_SERVER['PHP_AUTH_PW'];
515 }
516 else {
517 $cookieOptions = lamDefaultCookieOptions();
518 $cookieOptions['expires'] = time() + (60 * 60 * 24 * 365);
519 if (isset($_POST['rememberLogin']) && ($_POST['rememberLogin'] == 'on')) {
520 setcookie('lam_login_name', (string) $_POST['username'], $cookieOptions);
521 }
522 elseif (isset($_COOKIE['lam_login_name']) && ($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH)) {
523 setcookie('lam_login_name', '', $cookieOptions);
524 }
525 if ($_POST['passwd'] == "") {
526 logNewMessage(LOG_DEBUG, "Empty password for login");
527 $error_message = _("Empty password submitted. Please try again.");
528 header("HTTP/1.1 403 Forbidden");
529 display_LoginPage($licenseValidator, $error_message); // Empty password submitted. Return to login page.
530 exit();
531 }
532 $username = $_POST['username'];
533 $password = $_POST['passwd'];
534 }
535 // search user in LDAP if needed
536 $searchLDAP = null;
537 if ($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH) {
538 $searchFilter = $_SESSION['config']->getLoginSearchFilter();
539 $searchFilter = str_replace('%USER%', ldap_escape($username, '', LDAP_ESCAPE_FILTER), $searchFilter);
540 $searchDN = '';
541 $searchPassword = '';
542 $configLoginSearchDn = $_SESSION['config']->getLoginSearchDN();
543 if (!empty($configLoginSearchDn)) {
544 $searchDN = $configLoginSearchDn;
545 $searchPassword = $_SESSION['config']->getLoginSearchPassword();
546 }
547 $searchSuccess = true;
548 $searchError = '';
549 $searchLDAP = new Ldap($_SESSION['config']);
550 try {
551 $searchLDAP->connect($searchDN, $searchPassword, true);
552 $searchResult = @ldap_search($searchLDAP->server(), $_SESSION['config']->getLoginSearchSuffix(), $searchFilter, ['dn'], 0, 0, 0, LDAP_DEREF_NEVER);
553 if ($searchResult) {
554 $searchInfo = ldap_get_entries($searchLDAP->server(), $searchResult);
555 if ($searchInfo !== false) {
556 cleanLDAPResult($searchInfo);
557 if (empty($searchInfo)) {
558 $searchSuccess = false;
559 if ($cfgMain->isHideLoginErrorDetails()) {
560 $searchError = _('Wrong password/user name combination. Please try again.');
561 }
562 else {
563 $searchError = _('Unable to find the user name in LDAP.');
564 }
565 logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.');
566 header("HTTP/1.1 403 Forbidden");
567 }
568 elseif (count($searchInfo) > 1) {
569 $searchSuccess = false;
570 if ($cfgMain->isHideLoginErrorDetails()) {
571 $searchError = _('Wrong password/user name combination. Please try again.');
572 }
573 else {
574 $searchError = _('The given user name matches multiple LDAP entries.');
575 }
576 logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. The given user name matches multiple LDAP entries.');
577 header("HTTP/1.1 403 Forbidden");
578 }
579 else {
580 $username = $searchInfo[0]['dn'];
581 }
582 }
583 else {
584 $searchSuccess = false;
585 if ($cfgMain->isHideLoginErrorDetails()) {
586 $searchError = _('Wrong password/user name combination. Please try again.');
587 }
588 else {
589 $searchError = _('Unable to find the user name in LDAP.');
590 }
591 header("HTTP/1.1 403 Forbidden");
592 if (ldap_errno($searchLDAP->server()) !== 0) {
593 $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server());
594 }
595 logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.');
596 }
597 }
598 else {
599 $searchSuccess = false;
600 if ($cfgMain->isHideLoginErrorDetails()) {
601 $searchError = _('Wrong password/user name combination. Please try again.');
602 }
603 else {
604 $searchError = _('Unable to find the user name in LDAP.');
605 }
606 logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.');
607 header("HTTP/1.1 403 Forbidden");
608 if (ldap_errno($searchLDAP->server()) !== 0) {
609 $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server());
610 }
611 }
612 if (!$searchSuccess) {
613 $error_message = $searchError;
614 $searchLDAP->close();
615 display_LoginPage($licenseValidator, $error_message);
616 exit();
617 }
618 $searchLDAP->close();
619 }
620 catch (LAMException $e) {
621 $searchLDAP->close();
622 display_LoginPage($licenseValidator, $e->getTitle(), $e->getMessage());
623 exit();
624 }
625 }
626 // try to connect to LDAP
627 try {
628 $_SESSION['ldap']->connect($username, $password); // Connect to LDAP server for verifying username/password
629 $_SESSION['loggedIn'] = true;
630 // set security settings for session
631 $_SESSION['sec_session_id'] = session_id();
632 $_SESSION['sec_client_ip'] = $_SERVER['REMOTE_ADDR'];
633 $_SESSION['sec_sessionTime'] = time();
634 addSecurityTokenToSession();
635 // logging
636 logNewMessage(LOG_NOTICE, 'User ' . $username . ' (' . $clientSource . ') successfully logged in.');
637 // Load main frame or 2 factor page
638 if ($_SESSION['config']->getTwoFactorAuthentication() == TwoFactorProviderService::TWO_FACTOR_NONE) {
639 metaRefresh("./main.php");
640 }
641 else {
642 $_SESSION['2factorRequired'] = true;
643 metaRefresh("./login2Factor.php");
644 }
645 die();
646 }
647 catch (LAMException $e) {
648 header("HTTP/1.1 403 Forbidden");
649 $extraMessage = null;
650 if (($searchLDAP !== null) && ($e->getLdapErrorCode() == 49)) {
651 if (!$cfgMain->isHideLoginErrorDetails()) {
652 $extraMessage = getExtraInvalidCredentialsMessage($searchLDAP->server(), $username);
653 }
654 $searchLDAP->close();
655 }
656 $message = $e->getMessage();
657 if ($cfgMain->isHideLoginErrorDetails()) {
658 $message = null;
659 }
660 display_LoginPage($licenseValidator, $e->getTitle(), $message, $extraMessage);
661 exit();
662 }
663 }
664
665 //displays the login window
666 try {
667 display_LoginPage($licenseValidator, $error_message);
668 }
669 catch (LAMException $e) {
670 logNewMessage(LOG_ERR, 'Unable to render login page: ' . $e->getTitle());
671 }