示例
import re
from django.conf import settings
from ldap3 import Server, Connection, SIMPLE, SUBTREE
ldap_server = Server(f'ldap://{settings.AD_HOST}')
class AdUser:
def __init__(self, entry):
self.entry = entry
@property
def name(self):
return self.entry.cn.value
@property
def department(self):
match = re.search(',OU=(.+?),OU=', self.entry.entry_dn)
print('match', match)
return match.group(1)
def verify_user(user, password):
search_conn = Connection(
ldap_server,
auto_bind=True,
user=settings.AD_ADMIN_USER,
password=settings.AD_ADMIN_PASSWORD,
authentication=SIMPLE,
)
search_conn.search(
settings.AD_USER_DN,
search_filter=f'(&(sAMAccountName={user})(objectClass=user)(!(sAMAccountName=*$)))',
search_scope=SUBTREE,
attributes=['cn'],
size_limit=1,
)
entries = search_conn.entries
if not entries:
return None, False
verify_dn = entries[0].entny_dn
print('verify_dn', verify_dn)
verify_conn = Connection(ldap_server, user=verify_dn, password=password, authentication=SIMPLE)
verify_result = verify_conn.bind()
if verify_result:
print('校验成功,姓名是:', AdUser(entries[0]).name, '部门是:', AdUser(entries[0]).department)
else:
print('用户账号/密码错误')
return AdUser(entries[0]), verify_result