LDAP.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2011 Corentin Le Bail
  3. # Copyright © 2011-2016 Guillaume Ayoub
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. LDAP authentication.
  19. Authentication based on the ``python-ldap`` module
  20. (http://www.python-ldap.org/).
  21. """
  22. import ldap
  23. from .. import config, log
  24. BASE = config.get("auth", "ldap_base")
  25. ATTRIBUTE = config.get("auth", "ldap_attribute")
  26. FILTER = config.get("auth", "ldap_filter")
  27. CONNEXION = ldap.initialize(config.get("auth", "ldap_url"))
  28. BINDDN = config.get("auth", "ldap_binddn")
  29. PASSWORD = config.get("auth", "ldap_password")
  30. SCOPE = getattr(ldap, "SCOPE_%s" % config.get("auth", "ldap_scope").upper())
  31. def is_authenticated(user, password):
  32. """Check if ``user``/``password`` couple is valid."""
  33. global CONNEXION
  34. try:
  35. CONNEXION.whoami_s()
  36. except:
  37. log.LOGGER.debug("Reconnecting the LDAP server")
  38. CONNEXION = ldap.initialize(config.get("auth", "ldap_url"))
  39. if BINDDN and PASSWORD:
  40. log.LOGGER.debug("Initial LDAP bind as %s" % BINDDN)
  41. CONNEXION.simple_bind_s(BINDDN, PASSWORD)
  42. distinguished_name = "%s=%s" % (ATTRIBUTE, ldap.dn.escape_dn_chars(user))
  43. log.LOGGER.debug(
  44. "LDAP bind for %s in base %s" % (distinguished_name, BASE))
  45. if FILTER:
  46. filter_string = "(&(%s)%s)" % (distinguished_name, FILTER)
  47. else:
  48. filter_string = distinguished_name
  49. log.LOGGER.debug("Used LDAP filter: %s" % filter_string)
  50. users = CONNEXION.search_s(BASE, SCOPE, filter_string)
  51. if users:
  52. log.LOGGER.debug("User %s found" % user)
  53. try:
  54. CONNEXION.simple_bind_s(users[0][0], password or "")
  55. except ldap.LDAPError:
  56. log.LOGGER.debug("Invalid credentials")
  57. else:
  58. log.LOGGER.debug("LDAP bind OK")
  59. return True
  60. else:
  61. log.LOGGER.debug("User %s not found" % user)
  62. log.LOGGER.debug("LDAP bind failed")
  63. return False