Browse Source

Added LDAP login test

causefx 7 years ago
parent
commit
fe24bb7ab2
3 changed files with 133 additions and 4 deletions
  1. 84 2
      api/functions/homepage-connect-functions.php
  2. 9 0
      api/functions/organizr-functions.php
  3. 40 2
      js/functions.js

+ 84 - 2
api/functions/homepage-connect-functions.php

@@ -2320,6 +2320,87 @@ function testAPIConnection($array)
 				};
 			}
 			break;
+		case 'ldap_login':
+			$username = $array['data']['data']['username'];
+			$password = $array['data']['data']['password'];
+			if (empty($username) || empty($password)) {
+				return 'Missing Username or Password';
+			}
+			if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
+				$ad = new \Adldap\Adldap();
+				// Create a configuration array.
+				$ldapServers = explode(',', $GLOBALS['authBackendHost']);
+				$i = 0;
+				foreach ($ldapServers as $key => $value) {
+					// Calculate parts
+					$digest = parse_url(trim($value));
+					$scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
+					$host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
+					$port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
+					// Reassign
+					$ldapHosts[] = $host;
+					$ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
+					if ($i == 0) {
+						$ldapPort = $port;
+					}
+					$i++;
+				}
+				$config = [
+					// Mandatory Configuration Options
+					'hosts' => $ldapHosts,
+					'base_dn' => $GLOBALS['authBaseDN'],
+					'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
+					'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
+					// Optional Configuration Options
+					'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
+					'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
+					'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
+					'port' => $ldapPort,
+					'follow_referrals' => false,
+					'use_ssl' => false,
+					'use_tls' => false,
+					'version' => 3,
+					'timeout' => 5,
+					// Custom LDAP Options
+					'custom_options' => [
+						// See: http://php.net/ldap_set_option
+						//LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
+					]
+				];
+				// Add a connection provider to Adldap.
+				$ad->addProvider($config);
+				try {
+					// If a successful connection is made to your server, the provider will be returned.
+					$provider = $ad->connect();
+					//prettyPrint($provider);
+					if ($provider->auth()->attempt($username, $password, true)) {
+						// Passed.
+						//$user = $provider->search()->find($username);
+						//return $user->getUserPrincipalName();
+						//return $user->getGroups(['cn']);
+						return true;
+					} else {
+						// Failed.
+						return 'Username/Password Failed to authenticate';
+					}
+				} catch (\Adldap\Auth\BindException $e) {
+					$detailedError = $e->getDetailedError();
+					writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+					return $detailedError->getErrorMessage();
+					// There was an issue binding / connecting to the server.
+				} catch (Adldap\Auth\UsernameRequiredException $e) {
+					$detailedError = $e->getDetailedError();
+					writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+					return $detailedError->getErrorMessage();
+					// The user didn't supply a username.
+				} catch (Adldap\Auth\PasswordRequiredException $e) {
+					$detailedError = $e->getDetailedError();
+					writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+					return $detailedError->getErrorMessage();
+					// The user didn't supply a password.
+				}
+			}
+			break;
 		case 'ldap':
 			if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
 				$ad = new \Adldap\Adldap();
@@ -2367,8 +2448,9 @@ function testAPIConnection($array)
 					// If a successful connection is made to your server, the provider will be returned.
 					$provider = $ad->connect();
 				} catch (\Adldap\Auth\BindException $e) {
-					writeLog('error', 'LDAP Function - Error: ' . $e->getMessage(), 'SYSTEM');
-					return $e->getMessage();
+					$detailedError = $e->getDetailedError();
+					writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
+					return $detailedError->getErrorMessage();
 					// There was an issue binding / connecting to the server.
 				}
 				return ($provider) ? true : false;

+ 9 - 0
api/functions/organizr-functions.php

@@ -656,6 +656,15 @@ function getSettingsMain()
 				'attr' => 'onclick="testAPIConnection(\'ldap\')"',
 				'help' => 'Remember! Please save before using the test button!'
 			),
+			array(
+				'type' => 'button',
+				'name' => 'test-button-ldap-login',
+				'label' => 'Test Login',
+				'icon' => 'fa fa-flask',
+				'class' => 'ldapAuth switchAuth',
+				'text' => 'Test Login',
+				'attr' => 'onclick="showLDAPLoginTest()"'
+			),
 			array(
 				'type' => 'input',
 				'name' => 'embyURL',

+ 40 - 2
js/functions.js

@@ -5613,9 +5613,9 @@ function homepageRequests(timeout){
 	if(typeof timeouts['ombi-Homepage'] !== 'undefined'){ clearTimeout(timeouts['ombi-Homepage']); }
 	timeouts['ombi-Homepage'] = setTimeout(function(){ homepageRequests(timeout); }, timeout);
 }
-function testAPIConnection(service){
+function testAPIConnection(service, data = ''){
     messageSingle('',' Testing now...',activeInfo.settings.notifications.position,'#FFF','info','10000');
-    organizrAPI('POST','api/?v1/test/api/connection',{action:service}).success(function(data) {
+    organizrAPI('POST','api/?v1/test/api/connection',{action:service, data:data}).success(function(data) {
         try {
             var response = JSON.parse(data);
         }catch(e) {
@@ -6701,6 +6701,44 @@ function isJSON(data) {
         return false;
     }
 }
+function createElementFromHTML(htmlString) {
+    var div = document.createElement('div');
+    div.innerHTML = htmlString.trim();
+    return div.firstChild;
+}
+function showLDAPLoginTest(){
+    var div = `
+        <div class="row">
+            <div class="col-12">
+                <div class="card m-b-0">
+                    <div class="form-horizontal">
+                        <div class="card-body">
+                            <h4 class="card-title" lang="en">LDAP User Info</h4>
+                            <div class="form-group row">
+                                <div class="col-sm-12">
+                                    <input type="text" class="form-control" id="ldapUsernameTest" placeholder="Username">
+                                </div>
+                            </div>
+                            <div class="form-group row">
+                                <div class="col-sm-12">
+                                    <input type="password" class="form-control" id="ldapPasswordTest" placeholder="Password">
+                                </div>
+                            </div>
+                            <div class="form-group mb-0 p-r-10 text-right">
+                                <button type="submit" onclick="testAPIConnection('ldap_login', {'username':$('#ldapUsernameTest').val(),'password':$('#ldapPasswordTest').val()})" class="btn btn-info waves-effect waves-light">Test Login</button>
+                            </div>
+                        </div>				
+                    </div>
+                </div>
+            </div>
+        </div>
+    `;
+    swal({
+        content: createElementFromHTML(div),
+        buttons: false,
+        className: 'bg-org'
+    })
+}
 function launch(){
 	organizrConnect('api/?v1/launch_organizr').success(function (data) {
         try {