LDAP.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2011 Corentin Le Bail
  5. # Copyright © 2011 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 config, log
  26. BASE = config.get("acl", "ldap_base")
  27. ATTRIBUTE = config.get("acl", "ldap_attribute")
  28. CONNEXION = ldap.initialize(config.get("acl", "ldap_url"))
  29. PERSONAL = config.getboolean("acl", "personal")
  30. def has_right(owner, user, password):
  31. """Check if ``user``/``password`` couple is valid."""
  32. if (user != owner and PERSONAL) or not user:
  33. # User is not owner and personal calendars, or no user given, forbidden
  34. return False
  35. dn = "%s=%s" % (ATTRIBUTE, ldap.dn.escape_dn_chars(user))
  36. log.LOGGER.debug("LDAP bind for %s in base %s" % (dn, BASE))
  37. users = CONNEXION.search_s(BASE, ldap.SCOPE_ONELEVEL, dn)
  38. if users:
  39. log.LOGGER.debug("User %s found" % user)
  40. try:
  41. CONNEXION.simple_bind_s(users[0][0], password or "")
  42. except ldap.INVALID_CREDENTIALS:
  43. log.LOGGER.debug("Invalid credentials")
  44. else:
  45. log.LOGGER.debug("LDAP bind OK")
  46. return True
  47. else:
  48. log.LOGGER.debug("User %s not found" % user)
  49. log.LOGGER.debug("LDAP bind failed")
  50. return False