LDAP.py 2.5 KB

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