Commits

Peter Sagerson committed 38ce809

Support callable AUTH_LDAP_SERVER_URI.

Comments (0)

Files changed (3)

django_auth_ldap/backend.py

         Returns our cached LDAPObject, which may or may not be bound.
         """
         if self._connection is None:
-            self._connection = ldap.initialize(self.settings.SERVER_URI)
+            uri = self.settings.SERVER_URI
+            if callable(uri):
+                uri = uri()
+
+            self._connection = ldap.initialize(uri)
 
             for opt, value in self.settings.CONNECTION_OPTIONS.iteritems():
                 self._connection.set_option(opt, value)

django_auth_ldap/tests.py

 
         self.assertEqual(self.ldapobj.get_option('opt1'), 'value1')
 
+    def test_callable_server_uri(self):
+        self._init_settings(
+            SERVER_URI=lambda: 'ldap://ldap.example.com',
+            USER_DN_TEMPLATE='uid=%(user)s,ou=people,o=test'
+        )
+
+        self.backend.authenticate(username='alice', password='password')
+
+        ldapobj = self.mockldap['ldap://ldap.example.com']
+        self.assertEqual(
+            ldapobj.methods_called(with_args=True),
+            [('initialize', ('ldap://ldap.example.com',), {}),
+             ('simple_bind_s', ('uid=alice,ou=people,o=test', 'password'), {})]
+        )
+
     def test_simple_bind(self):
         self._init_settings(
             USER_DN_TEMPLATE='uid=%(user)s,ou=people,o=test'

docs/source/authentication.rst

 
     AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
 
+If your server location is even more dynamic than this, you may provide a
+function (or any callable object) that returns the URI. You should assume that
+this will be called on every request, so if it's an expensive operation, some
+caching is in order.
+
+.. code-block:: python
+
+    from my_module import find_my_ldap_server
+
+    AUTH_LDAP_SERVER_URI = find_my_ldap_server
+
 If you need to configure any python-ldap options, you can set
 :setting:`AUTH_LDAP_GLOBAL_OPTIONS` and/or
 :setting:`AUTH_LDAP_CONNECTION_OPTIONS`. For example, disabling referrals is not