Commits

Felipe Prenholato committed 9f5783e

Adding support to multiple connections.

Comments (0)

Files changed (2)

django_auth_ldap/backend.py

 from django.contrib.auth.models import User, Group, SiteProfileNotAvailable
 from django.core.cache import cache
 from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
+from django.utils.datastructures import SortedDict
 import django.dispatch
 
 from django_auth_ldap.config import _LDAPConfig, LDAPSearch, LDAPGroupType
     #
 
     def authenticate(self, username, password):
-        ldap_user = _LDAPUser(self, username=username)
-        user = ldap_user.authenticate(password)
-        
+        for name in ldap_settings.AUTH_LDAP_CONNECTIONS:
+            ldap_user = _LDAPUser(self, using=name, username=username)
+            user = ldap_user.authenticate(password)
+            if user is not None:
+                self.using = name
+                break
+
         return user
-    
+
     def get_user(self, user_id):
         user = None
-        
+
         try:
             user = User.objects.get(pk=user_id)
-            _LDAPUser(self, user=user) # This sets user.ldap_user
+            for name in ldap_settings.AUTH_LDAP_CONNECTIONS:
+                _LDAPUser(self, using=name, user=user) # This sets user.ldap_user
+                if user is not None:
+                    self.using = name
+                    break
         except User.DoesNotExist:
             pass
         
 
     def get_group_permissions(self, user):
         if not hasattr(user, 'ldap_user') and ldap_settings.AUTH_LDAP_AUTHORIZE_ALL_USERS:
-            _LDAPUser(self, user=user) # This sets user.ldap_user
+            _LDAPUser(self, self.using, user=user) # This sets user.ldap_user
         
         if hasattr(user, 'ldap_user'):
             return user.ldap_user.get_group_permissions()
     #
 
     def populate_user(self, username):
-        ldap_user = _LDAPUser(self, username=username)
+        ldap_user = _LDAPUser(self, using=self.using, username=username)
         user = ldap_user.populate_user()
         
         return user
     # Initialization
     #
     
-    def __init__(self, backend, username=None, user=None):
+    def __init__(self, backend, using, username=None, user=None):
         """
         A new LDAPUser must be initialized with either a username or an
         authenticated User object. If a user is given, the username will be
         ignored.
         """
         self.backend = backend
+        self.using = using
         self.ldap = backend.ldap_module()
         self._username = username
         self._user_dn = None
 
     def __deepcopy__(self, memo):
         obj = object.__new__(self.__class__)
+        obj.using = self.using
         obj.backend = self.backend
         obj.ldap = self.ldap
         obj._user = copy.deepcopy(self._user, memo)
         obj._user_attrs = self._user_attrs
         obj._groups = self._groups
         obj._group_permissions = self._group_permissions
-        
+
         # The connection couldn't be copied even if we wanted to
         obj._connection = self._connection
         obj._connection_bound = self._connection_bound
         Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
         Populates self._user_dn and self._user_attrs.
         """
-        search = ldap_settings.AUTH_LDAP_USER_SEARCH
+        search = ldap_settings.get_search_for(self.using)
         if search is None:
             raise ImproperlyConfigured('AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.')
         
         Binds to the LDAP server with AUTH_LDAP_BIND_DN and
         AUTH_LDAP_BIND_PASSWORD.
         """
-        self._bind_as(ldap_settings.AUTH_LDAP_BIND_DN,
-            ldap_settings.AUTH_LDAP_BIND_PASSWORD)
+        self._bind_as(ldap_settings.get_conn_for(self.using)['USER'],
+            ldap_settings.get_conn_for(self.using)['PASSWORD'])
 
         self._connection_bound = True
 
         Returns our cached LDAPObject, which may or may not be bound.
         """
         if self._connection is None:
-            self._connection = self.ldap.initialize(ldap_settings.AUTH_LDAP_SERVER_URI)
-            
+            self._connection = self.ldap.initialize(ldap_settings.get_conn_for(self.using)['NAME'])
+
             for opt, value in ldap_settings.AUTH_LDAP_CONNECTION_OPTIONS.iteritems():
                 self._connection.set_option(opt, value)
 
 
         return self._connection
 
-
-
 class _LDAPUserGroups(object):
     """
     Represents the set of groups that a user belongs to.
     def _cache_key(self, attr_name):
         return u'auth_ldap.%s.%s.%s' % (self.__class__.__name__, attr_name, self._ldap_user.dn)
 
-
 class LDAPSettings(object):
     """
     This is a simple class to take the place of the global settings object. An
         'AUTH_LDAP_BIND_PASSWORD': '',
         'AUTH_LDAP_CACHE_GROUPS': False,
         'AUTH_LDAP_CONNECTION_OPTIONS': {},
+        'AUTH_LDAP_CONNECTIONS': [],
         'AUTH_LDAP_FIND_GROUP_PERMS': False,
         'AUTH_LDAP_GLOBAL_OPTIONS': {},
         'AUTH_LDAP_GROUP_CACHE_TIMEOUT': None,
         'AUTH_LDAP_USER_FLAGS_BY_GROUP': {},
         'AUTH_LDAP_USER_SEARCH': None,
     }
+
+    connections = SortedDict()
     
     def __init__(self):
         """
             value = getattr(settings, name, default)
             setattr(self, name, value)
 
+        if not self.AUTH_LDAP_CONNECTIONS:
+            self.AUTH_LDAP_CONNECTIONS = ['ldap']
+            self.connections['ldap'] = {
+                'NAME': self.AUTH_LDAP_SERVER_URI,
+                'USER': self.AUTH_LDAP_BIND_DN,
+                'PASSWORD': self.AUTH_LDAP_BIND_PASSWORD,
+                'USER_SEARCH': self.AUTH_LDAP_USER_SEARCH,
+                'BASE_DN': self.AUTH_LDAP_USER_SEARCH.base_dn,
+            }
+        else:
+            for name in self.AUTH_LDAP_CONNECTIONS:
+                s = settings.DATABASES.get(name,None)
+                if not s:
+                    raise ImproperlyConfigured,u"Connection %s not found in settings.DATABASES" % name
+                self.connections[name] = settings.DATABASES[name]
+
+    def get_conn_for(self,alias):
+        return self.connections[alias]
+
+    def get_search_for(self,alias):
+        return self.connections[alias]['USER_SEARCH']
 
 # Our global settings object
 ldap_settings = LDAPSettings()
+# LDAPBackend().authenticate('teste.ad01.pdgr@pdg.com.br','jmEiEywxPx4io')

django_auth_ldap/config.py

                     pass
 
             cls.logger = logging.getLogger('django_auth_ldap')
-            #cls.logger.addHandler(NullHandler())
+            cls.logger.addHandler(NullHandler())
 
         return cls.logger
     get_logger = classmethod(get_logger)