Skip to content

Commit

Permalink
Update util.py
Browse files Browse the repository at this point in the history
由于管理后台填写的测试用户,已经固定好了DN信息,当ldap用户在多OU环境(多个部门组织架构)则无法登陆。
  • Loading branch information
ivonlee authored Sep 11, 2018
1 parent a7d6f82 commit 47b4476
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions src/libs/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import ssl
import time
import ldap3
from ldap3 import Server, Connection, SUBTREE
import configparser
import ast

Expand Down Expand Up @@ -105,24 +106,57 @@ def test_auth(username, password, host, type, sc, domain):
def auth(username, password):
un_init = init_conf()
ldap = ast.literal_eval(un_init['ldap'])
# 后台录入的验证用户信息,连接到ldap后通过查询登陆的用户名所在的OU,DN信息,然后进一步去ldap服务器进行账户和密码验证。
LDAP_ADMIN_USER = ldap['user']
LDAP_ADMIN_PASS = ldap['password']

LDAP_SERVER = ldap['host']
LDAP_DOMAIN = ldap['domain']
LDAP_TYPE = ldap['type']
LDAP_SCBASE = ldap['sc']
# 这里前端可以做个基础DN录入,搜索范围锁定在这个DN下
SEARCH_BASE = ldap['sc']

if LDAP_TYPE == '1':
user = username + '@' + LDAP_DOMAIN
elif LDAP_TYPE == '2':
user = "uid=%s,%s" % (username, LDAP_SCBASE)
user = "uid=%s,%s" % (LDAP_ADMIN_USER, LDAP_SCBASE)
else:
user = "cn=%s,%s" % (username, LDAP_SCBASE)
user = "cn=%s,%s" % (LDAP_ADMIN_USER, LDAP_SCBASE)
c = ldap3.Connection(
ldap3.Server(LDAP_SERVER, get_info=ldap3.ALL),
user=user,
password=password)
password=LDAP_ADMIN_PASS)
ret = c.bind()
if ret:
c.unbind()
return True
res = c.search(
search_base = SEARCH_BASE,
search_filter = '(cn={})'.format(username),
search_scope = SUBTREE,
attributes = ['cn', 'uid', 'mail'],
)
if res:
entry = c.response[0]
dn = entry['dn']
attr_dict = entry['attributes']

# check password by dn
try:
conn2 = Connection(ldap3.Server(LDAP_SERVER, get_info=ldap3.ALL), user=dn, password=password, check_names=True, lazy=False, raise_exceptions=False)
conn2.bind()
if conn2.result["description"] == "success":
print((True, attr_dict["mail"], attr_dict["cn"], attr_dict["uid"]))
c.unbind()
conn2.unbind()
return True
else:
print("auth fail")
return False
except Exception as e:
print("auth fail")
return False
else:
return False
else:
return False

Expand Down

0 comments on commit 47b4476

Please sign in to comment.