ldap.py 1.2 KB

123456789101112131415161718192021222324252627282930
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. import ldap
  5. class LDAP:
  6. def __init__(self, server, port, rules, admin_dn, password, base_dn):
  7. self.server = server
  8. self.port = port
  9. self.rules = rules
  10. self.admin_dn = admin_dn
  11. self.password = password
  12. self.base_dn = base_dn
  13. def valid_user(self, username, password):
  14. try:
  15. conn = ldap.initialize("ldap://{0}:{1}".format(self.server, self.port), bytes_mode=False)
  16. conn.simple_bind_s(self.admin_dn, self.password)
  17. search_filter = f'({self.rules}={username})'
  18. ldap_result_id = conn.search(self.base_dn, ldap.SCOPE_SUBTREE, search_filter, None)
  19. result_type, result_data = conn.result(ldap_result_id, 0)
  20. if result_type == ldap.RES_SEARCH_ENTRY:
  21. conn.simple_bind_s(result_data[0][0], password)
  22. return True, None
  23. else:
  24. return False, None
  25. except Exception as error:
  26. args = error.args
  27. return False, args[0].get('desc', '未知错误') if args else '%s' % error