فهرست منبع

fix ldap test buttons for 2.1

CauseFX 5 سال پیش
والد
کامیت
a636c2a52f
4فایلهای تغییر یافته به همراه211 افزوده شده و 157 حذف شده
  1. 162 4
      api/functions/auth-functions.php
  2. 1 151
      api/functions/homepage-connect-functions.php
  3. 46 0
      api/v2/routes/connectionTester.php
  4. 2 2
      js/functions.js

+ 162 - 4
api/functions/auth-functions.php

@@ -2,9 +2,167 @@
 
 trait AuthFunctions
 {
-	public function testing()
+	public function testConnectionLdap()
 	{
-		return 'wasssup';
+		if (!empty($this->config['authBaseDN']) && !empty($this->config['authBackendHost'])) {
+			$ad = new \Adldap\Adldap();
+			// Create a configuration array.
+			$ldapServers = explode(',', $this->config['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;
+				if ($i == 0) {
+					$ldapPort = $port;
+				}
+				$i++;
+			}
+			$config = [
+				// Mandatory Configuration Options
+				'hosts' => $ldapHosts,
+				'base_dn' => $this->config['authBaseDN'],
+				'username' => (empty($this->config['ldapBindUsername'])) ? null : $this->config['ldapBindUsername'],
+				'password' => (empty($this->config['ldapBindPassword'])) ? null : $this->decrypt($this->config['ldapBindPassword']),
+				// Optional Configuration Options
+				'schema' => (($this->config['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($this->config['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
+				'account_prefix' => '',
+				'account_suffix' => '',
+				'port' => $ldapPort,
+				'follow_referrals' => false,
+				'use_ssl' => $this->config['ldapSSL'],
+				'use_tls' => $this->config['ldapTLS'],
+				'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();
+			} catch (\Adldap\Auth\BindException $e) {
+				$detailedError = $e->getDetailedError();
+				$this->writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
+				$this->setAPIResponse('error', $detailedError->getErrorMessage(), 409);
+				return $detailedError->getErrorMessage();
+				// There was an issue binding / connecting to the server.
+			}
+			if ($provider) {
+				$this->setAPIResponse('success', 'LDAP connection successful', 200);
+				return true;
+			} else {
+				$this->setAPIResponse('error', 'Could not connect', 500);
+				return false;
+			}
+			return ($provider) ? true : false;
+		} else {
+			$this->setAPIResponse('error', 'authBaseDN and/or BackendHost not supplied', 422);
+			return false;
+		}
+	}
+	
+	public function testConnectionLdapLogin($array)
+	{
+		$username = $array['username'] ?? null;
+		$password = $array['password'] ?? null;
+		if (empty($username) || empty($password)) {
+			$this->setAPIResponse('error', 'Username and/or Password not supplied', 422);
+			return false;
+		}
+		if (!empty($this->config['authBaseDN']) && !empty($this->config['authBackendHost'])) {
+			$ad = new \Adldap\Adldap();
+			// Create a configuration array.
+			$ldapServers = explode(',', $this->config['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' => $this->config['authBaseDN'],
+				'username' => (empty($this->config['ldapBindUsername'])) ? null : $this->config['ldapBindUsername'],
+				'password' => (empty($this->config['ldapBindPassword'])) ? null : $this->decrypt($this->config['ldapBindPassword']),
+				// Optional Configuration Options
+				'schema' => (($this->config['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($this->config['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
+				'account_prefix' => (empty($this->config['authBackendHostPrefix'])) ? null : $this->config['authBackendHostPrefix'],
+				'account_suffix' => (empty($this->config['authBackendHostSuffix'])) ? null : $this->config['authBackendHostSuffix'],
+				'port' => $ldapPort,
+				'follow_referrals' => false,
+				'use_ssl' => $this->config['ldapSSL'],
+				'use_tls' => $this->config['ldapTLS'],
+				'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->getFirstAttribute('cn');
+					//return $user->getGroups(['cn']);
+					//return $user;
+					//return $user->getUserPrincipalName();
+					//return $user->getGroups(['cn']);
+					$this->setAPIResponse('success', 'LDAP connection successful', 200);
+					return true;
+				} else {
+					// Failed.
+					$this->setAPIResponse('error', 'Username/Password Failed to authenticate', 401);
+					return false;
+				}
+			} catch (\Adldap\Auth\BindException $e) {
+				$detailedError = $e->getDetailedError();
+				$this->writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+				$this->setAPIResponse('error', $detailedError->getErrorMessage(), 500);
+				return $detailedError->getErrorMessage();
+				// There was an issue binding / connecting to the server.
+			} catch (Adldap\Auth\UsernameRequiredException $e) {
+				$detailedError = $e->getDetailedError();
+				$this->writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+				$this->setAPIResponse('error', $detailedError->getErrorMessage(), 422);
+				return $detailedError->getErrorMessage();
+				// The user didn't supply a username.
+			} catch (Adldap\Auth\PasswordRequiredException $e) {
+				$detailedError = $e->getDetailedError();
+				$this->writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
+				$this->setAPIResponse('error', $detailedError->getErrorMessage(), 422);
+				return $detailedError->getErrorMessage();
+				// The user didn't supply a password.
+			}
+		} else {
+			$this->setAPIResponse('error', 'authBaseDN and/or BackendHost not supplied', 422);
+			return false;
+		}
 	}
 	
 	public function checkPlexToken($token = '')
@@ -26,7 +184,7 @@ trait AuthFunctions
 			}
 			
 		} catch (Requests_Exception $e) {
-			$this->writeLog('success', 'Plex Token Check Function - Error: ' . $e->getMessage(), SYSTEM);
+			$this->writeLog('success', 'Plex Token Check Function - Error: ' . $e->getMessage(), 'SYSTEM');
 		}
 		return false;
 	}
@@ -144,7 +302,7 @@ trait AuthFunctions
 				'username' => (empty($this->config['ldapBindUsername'])) ? null : $this->config['ldapBindUsername'],
 				'password' => (empty($this->config['ldapBindPassword'])) ? null : $this->decrypt($this->config['ldapBindPassword']),
 				// Optional Configuration Options
-				'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
+				'schema' => (($this->config['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($this->config['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
 				'account_prefix' => (empty($this->config['authBackendHostPrefix'])) ? null : $this->config['authBackendHostPrefix'],
 				'account_suffix' => (empty($this->config['authBackendHostSuffix'])) ? null : $this->config['authBackendHostSuffix'],
 				'port' => $ldapPort,

+ 1 - 151
api/functions/homepage-connect-functions.php

@@ -90,154 +90,4 @@ trait HomepageConnectFunctions
 		}
 		return false;
 	}
-}
-
-
-function testAPIConnection($array)
-{
-	switch ($array['data']['action']) {
-		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' => $GLOBALS['ldapSSL'],
-					'use_tls' => $GLOBALS['ldapTLS'],
-					'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->getFirstAttribute('cn');
-						//return $user->getGroups(['cn']);
-						//return $user;
-						//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();
-				// 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;
-					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' => '',
-					'account_suffix' => '',
-					'port' => $ldapPort,
-					'follow_referrals' => false,
-					'use_ssl' => $GLOBALS['ldapSSL'],
-					'use_tls' => $GLOBALS['ldapTLS'],
-					'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();
-				} catch (\Adldap\Auth\BindException $e) {
-					$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;
-			}
-			return false;
-			break;
-		default :
-			return false;
-	}
-	return false;
-}
+}

+ 46 - 0
api/v2/routes/connectionTester.php

@@ -5,6 +5,52 @@
  *     description="Test Connections"
  * )
  */
+$app->post('/test/ldap', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     security={{ "api_key":{} }},
+	 *     tags={"test connection"},
+	 *     path="/api/v2/test/ldap",
+	 *     summary="Test LDAP connection",
+	 *     @OA\Response(response="200",description="Success",@OA\JsonContent(ref="#/components/schemas/success-message")),
+	 *     @OA\Response(response="401",description="Unauthorized",@OA\JsonContent(ref="#/components/schemas/unauthorized-message")),
+	 *     @OA\Response(response="404",description="Error",@OA\JsonContent(ref="#/components/schemas/error-message")),
+	 *     @OA\Response(response="409",description="Error",@OA\JsonContent(ref="#/components/schemas/error-message")),
+	 * )
+	 */
+	$Organizr = ($request->getAttribute('Organizr')) ?? new Organizr();
+	if ($Organizr->qualifyRequest(1, true)) {
+		$Organizr->testConnectionLdap();
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+	
+});
+$app->post('/test/ldap/login', function ($request, $response, $args) {
+	/**
+	 * @OA\Post(
+	 *     security={{ "api_key":{} }},
+	 *     tags={"test connection"},
+	 *     path="/api/v2/test/ldap/login",
+	 *     summary="Test LDAP connection using account login",
+	 *     @OA\Response(response="200",description="Success",@OA\JsonContent(ref="#/components/schemas/success-message")),
+	 *     @OA\Response(response="401",description="Unauthorized",@OA\JsonContent(ref="#/components/schemas/unauthorized-message")),
+	 *     @OA\Response(response="404",description="Error",@OA\JsonContent(ref="#/components/schemas/error-message")),
+	 *     @OA\Response(response="409",description="Error",@OA\JsonContent(ref="#/components/schemas/error-message")),
+	 * )
+	 */
+	$Organizr = ($request->getAttribute('Organizr')) ?? new Organizr();
+	if ($Organizr->qualifyRequest(1, true)) {
+		$Organizr->testConnectionLdapLogin($Organizr->apiData($request));
+	}
+	$response->getBody()->write(jsonE($GLOBALS['api']));
+	return $response
+		->withHeader('Content-Type', 'application/json;charset=UTF-8')
+		->withStatus($GLOBALS['responseCode']);
+	
+});
 $app->post('/test/iframe', function ($request, $response, $args) {
 	/**
 	 * @OA\Post(

+ 2 - 2
js/functions.js

@@ -6976,7 +6976,7 @@ function testAPIConnection(service, data = ''){
             return false;
         }
     }).fail(function(xhr) {
-	    message('API Error', xhr.responseJSON.response.message, activeInfo.settings.notifications.position, '#FFF', 'error', '10000');
+	    messageSingle('API Error', xhr.responseJSON.response.message, activeInfo.settings.notifications.position, '#FFF', 'error', '10000');
 	    console.error("Organizr Function: API Connection Failed | Error: " + xhr.responseJSON.response.message);
     });
 }
@@ -10048,7 +10048,7 @@ function showLDAPLoginTest(){
                                 </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>
+                                <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>