#!/usr/bin/env python # -*- coding: utf-8 -*- """Test LDAP connection and authentication""" import os import sys from ldap3 import Server, Connection, SUBTREE, ALL_ATTRIBUTES from dotenv import load_dotenv # Load environment variables load_dotenv() def test_ldap_connection(): """Test LDAP connection""" print("=" * 50) print("Testing LDAP Connection") print("=" * 50) # Get LDAP configuration ldap_server = os.getenv('LDAP_SERVER', 'ldap://panjit.com.tw') ldap_port = int(os.getenv('LDAP_PORT', 389)) ldap_bind_user = os.getenv('LDAP_BIND_USER_DN', '') ldap_bind_password = os.getenv('LDAP_BIND_USER_PASSWORD', '') ldap_search_base = os.getenv('LDAP_SEARCH_BASE', 'DC=panjit,DC=com,DC=tw') print(f"LDAP Server: {ldap_server}") print(f"LDAP Port: {ldap_port}") print(f"Bind User: {ldap_bind_user}") print(f"Search Base: {ldap_search_base}") print("-" * 50) try: # Create server object server = Server( ldap_server, port=ldap_port, use_ssl=False, get_info=ALL_ATTRIBUTES ) print("Creating LDAP connection...") # Create connection with bind user conn = Connection( server, user=ldap_bind_user, password=ldap_bind_password, auto_bind=True, raise_exceptions=True ) print("[OK] Successfully connected to LDAP server") print(f"[OK] Server info: {conn.server}") # Test search print("\nTesting LDAP search...") search_filter = "(objectClass=person)" conn.search( ldap_search_base, search_filter, SUBTREE, attributes=['sAMAccountName', 'displayName', 'mail'], size_limit=5 ) print(f"[OK] Found {len(conn.entries)} entries") if conn.entries: print("\nSample users:") for i, entry in enumerate(conn.entries[:3], 1): print(f" {i}. {entry.sAMAccountName} - {entry.displayName}") conn.unbind() print("\n[OK] LDAP connection test successful!") return True except Exception as e: print(f"\n[ERROR] LDAP connection failed: {str(e)}") print(f"Error type: {type(e).__name__}") return False def test_user_authentication(username, password): """Test user authentication""" print("\n" + "=" * 50) print(f"Testing authentication for user: {username}") print("=" * 50) # Get LDAP configuration ldap_server = os.getenv('LDAP_SERVER', 'ldap://panjit.com.tw') ldap_port = int(os.getenv('LDAP_PORT', 389)) ldap_bind_user = os.getenv('LDAP_BIND_USER_DN', '') ldap_bind_password = os.getenv('LDAP_BIND_USER_PASSWORD', '') ldap_search_base = os.getenv('LDAP_SEARCH_BASE', 'DC=panjit,DC=com,DC=tw') ldap_user_attr = os.getenv('LDAP_USER_LOGIN_ATTR', 'userPrincipalName') try: # Create server object server = Server( ldap_server, port=ldap_port, use_ssl=False, get_info=ALL_ATTRIBUTES ) # First, bind with service account to search for user conn = Connection( server, user=ldap_bind_user, password=ldap_bind_password, auto_bind=True, raise_exceptions=True ) # Search for user search_filter = f"(&(objectClass=person)({ldap_user_attr}={username}))" print(f"Searching with filter: {search_filter}") conn.search( ldap_search_base, search_filter, SUBTREE, attributes=['sAMAccountName', 'displayName', 'mail', 'userPrincipalName', 'distinguishedName'] ) if not conn.entries: print(f"[ERROR] User not found: {username}") return False user_entry = conn.entries[0] user_dn = user_entry.distinguishedName.value print(f"[OK] User found:") print(f" DN: {user_dn}") print(f" sAMAccountName: {user_entry.sAMAccountName}") print(f" displayName: {user_entry.displayName}") print(f" mail: {user_entry.mail}") # Try to bind with user credentials print(f"\nAttempting to authenticate user...") user_conn = Connection( server, user=user_dn, password=password, auto_bind=True, raise_exceptions=True ) print("[OK] Authentication successful!") user_conn.unbind() conn.unbind() return True except Exception as e: print(f"[ERROR] Authentication failed: {str(e)}") return False if __name__ == "__main__": # Test basic connection if test_ldap_connection(): # If you want to test user authentication, uncomment and modify: # test_user_authentication("your_username@panjit.com.tw", "your_password") pass else: print("\n[WARNING] Please check your LDAP configuration in .env file") sys.exit(1)