import ldap3
from ldap3 import Server, Connection, ALL
import sys
import io

# 設定 UTF-8 編碼
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

def test_ldap_auth():
    """測試 LDAP 認證功能"""
    server = Server('panjit.com.tw', port=389, use_ssl=False, get_info=ALL)
    
    try:
        # 使用正確的密碼測試
        print("測試 LDAP 認證...")
        print("伺服器: panjit.com.tw:389")
        print("帳號: ymirliu@panjit.com.tw")
        print("密碼: 3EDC4rfv5tgb")
        
        conn = Connection(
            server,
            user='ymirliu@panjit.com.tw',
            password='3EDC4rfv5tgb',
            auto_bind=True
        )
        
        print("\n✅ LDAP 認證成功！")
        print(f"認證用戶: {conn.user}")
        
        # 搜尋用戶資訊
        search_base = 'OU=PANJIT,DC=panjit,DC=com,DC=tw'
        conn.search(
            search_base,
            '(userPrincipalName=ymirliu@panjit.com.tw)',
            attributes=['cn', 'mail', 'memberOf', 'displayName']
        )
        
        if conn.entries:
            user = conn.entries[0]
            print(f"\n用戶詳細資訊:")
            print(f"  顯示名稱: {user.displayName if hasattr(user, 'displayName') else 'N/A'}")
            print(f"  CN: {user.cn if hasattr(user, 'cn') else 'N/A'}")
            print(f"  電子郵件: {user.mail if hasattr(user, 'mail') else 'N/A'}")
            
            # 檢查是否為管理員
            if hasattr(user, 'mail') and str(user.mail).lower() == 'ymirliu@panjit.com.tw':
                print(f"  管理員權限: ✅ 是")
            else:
                print(f"  管理員權限: ❌ 否")
                
            print("\n✅ LDAP 認證測試完全通過！")
        else:
            print("⚠️ 無法獲取用戶詳細資訊")
        
        conn.unbind()
        return True
        
    except ldap3.core.exceptions.LDAPBindError as e:
        print(f"\n❌ LDAP 認證失敗 (綁定錯誤): {e}")
        return False
    except Exception as e:
        print(f"\n❌ LDAP 連線錯誤: {e}")
        return False

if __name__ == "__main__":
    test_ldap_auth()