auth.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """
  2. LDAP authentication backend for ArchiveBox.
  3. This module extends django-auth-ldap to support the LDAP_CREATE_SUPERUSER flag.
  4. """
  5. __package__ = "archivebox.ldap"
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from django.contrib.auth.models import User
  9. from django_auth_ldap.backend import LDAPBackend as BaseLDAPBackend
  10. else:
  11. try:
  12. from django_auth_ldap.backend import LDAPBackend as BaseLDAPBackend
  13. except ImportError:
  14. # If django-auth-ldap is not installed, create a dummy base class
  15. class BaseLDAPBackend:
  16. """Dummy LDAP backend when django-auth-ldap is not installed."""
  17. pass
  18. class ArchiveBoxLDAPBackend(BaseLDAPBackend):
  19. """
  20. Custom LDAP authentication backend for ArchiveBox.
  21. Extends django-auth-ldap's LDAPBackend to support:
  22. - LDAP_CREATE_SUPERUSER: Automatically grant superuser privileges to LDAP users
  23. """
  24. def authenticate_ldap_user(self, ldap_user, password):
  25. """
  26. Authenticate using LDAP and optionally grant superuser privileges.
  27. This method is called by django-auth-ldap after successful LDAP authentication.
  28. """
  29. from archivebox.config.ldap import LDAP_CONFIG
  30. user = super().authenticate_ldap_user(ldap_user, password)
  31. if user and LDAP_CONFIG.LDAP_CREATE_SUPERUSER:
  32. # Grant superuser privileges to all LDAP-authenticated users
  33. if not user.is_superuser:
  34. user.is_superuser = True
  35. user.is_staff = True
  36. user.save()
  37. return user