Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented functionalities to allow multiple LDAP configs #281

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions django_python3_ldap/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
21 changes: 19 additions & 2 deletions django_python3_ldap/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions django_python3_ldap/ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down