diff --git a/django_python3_ldap/auth.py b/django_python3_ldap/auth.py index cba93fd..1f341e2 100644 --- a/django_python3_ldap/auth.py +++ b/django_python3_ldap/auth.py @@ -20,4 +20,7 @@ class LDAPBackend(ModelBackend): supports_inactive_user = False def authenticate(self, *args, **kwargs): + if hasattr(self, 'PREFIX'): + kwargs = dict(kwargs, prefix=self.PREFIX) + return ldap.authenticate(*args, **kwargs) diff --git a/django_python3_ldap/conf.py b/django_python3_ldap/conf.py index a548c47..a6af224 100644 --- a/django_python3_ldap/conf.py +++ b/django_python3_ldap/conf.py @@ -19,7 +19,13 @@ def __init__(self, name, default=None): def __get__(self, obj, cls): if obj is None: return self - return getattr(obj._settings, self.name, self.default) + + property_name = self.name + + if hasattr(obj._settings, (name_with_prefix := obj._prefix + self.name)): + property_name = name_with_prefix + + return getattr(obj._settings, property_name, self.default) class LazySettings(object): @@ -31,8 +37,19 @@ class LazySettings(object): to change settings at runtime. """ - def __init__(self, settings): + def __init__(self, settings, prefix=''): self._settings = settings + self._prefix = prefix + + def set_or_clear_prefix(self, new_prefix=''): + """ + Setter method for the _prefix property, is called before each authentication. + This allows users to use multiple LDAP configs at the same time. + + Args: + new_prefix (str, optional): The string that should be appended to the default constant names. Defaults to an empty string. + """ + self._prefix = new_prefix LDAP_AUTH_URL = LazySetting( name="LDAP_AUTH_URL", diff --git a/django_python3_ldap/ldap.py b/django_python3_ldap/ldap.py index 54d0bb4..00d04f1 100644 --- a/django_python3_ldap/ldap.py +++ b/django_python3_ldap/ldap.py @@ -251,6 +251,12 @@ def authenticate(*args, **kwargs): in settings.LDAP_AUTH_USER_LOOKUP_FIELDS, plus a `password` argument. """ password = kwargs.pop("password", None) + + if settings_prefix := kwargs.pop("prefix", None): + settings.set_or_clear_prefix(settings_prefix) + else: + settings.set_or_clear_prefix() + auth_user_lookup_fields = frozenset(settings.LDAP_AUTH_USER_LOOKUP_FIELDS) ldap_kwargs = { key: value for (key, value) in kwargs.items()