-def convert(field, value, func):
- if not value or field == 'jpegPhoto':
- return value
- elif isinstance(value, int):
- return str(value)
- elif isinstance(value, list):
- return [ func(x) for x in value ]
- else:
- return func(value)
-
-class LdapConnection(object):
- def __init__(self, server, bind_dn, bind_password):
- self.connection = ldap.initialize(server)
- self.connection.simple_bind_s(bind_dn, bind_password)
- self.charset = "utf-8"
-
- def add_s(self, dn, modlist):
- mods = []
- for field, value in modlist:
- converted = convert(field, value, lambda x: x.encode(self.charset))
- if isinstance(converted, list):
- mods.append((field, converted))
- else:
- mods.append((field, [converted]))
- return self.connection.add_s(dn.encode(self.charset), mods)
-
- def delete_s(self, dn):
- return self.connection.delete_s(dn.encode(self.charset))
-
- def modify_s(self, dn, modlist):
- mods = []
- for op, field, value in modlist:
- mods.append((op, field, convert(field, value, lambda x: x.encode(self.charset))))
- return self.connection.modify_s(dn.encode(self.charset), mods)
-
- def rename_s(self, dn, newrdn):
- return self.connection.rename_s(dn.encode(self.charset), newrdn.encode(self.charset))
-
- def search_s(self, base, scope, filterstr, attrlist):
- results = self.connection.search_s(base, scope, filterstr.encode(self.charset), attrlist)
- output = []
- for dn, attrs in results:
- for field in attrs:
- if field == "member" or field == "memberUid":
- attrs[field] = convert(field, attrs[field], lambda x: x.decode(self.charset))
- else:
- attrs[field] = convert(field, attrs[field][0], lambda x: x.decode(self.charset))
- output.append((dn.decode(self.charset), attrs))
- return output
-
-# FIXME: is this the right place to initialize the LDAP connection?
-connection = LdapConnection(settings.LDAPDB_SERVER_URI,
- settings.LDAPDB_BIND_DN,
- settings.LDAPDB_BIND_PASSWORD)
-
+from ldapdb.router import Router
+
+def escape_ldap_filter(value):
+ value = unicode(value)
+ return value.replace('\\', '\\5c') \
+ .replace('*', '\\2a') \
+ .replace('(', '\\28') \
+ .replace(')', '\\29') \
+ .replace('\0', '\\00')
+
+# Add the LDAP backend
+settings.DATABASES['ldap'] = {
+ 'ENGINE': 'ldapdb.backends.ldap',
+ 'NAME': settings.LDAPDB_SERVER_URI,
+ 'USER': settings.LDAPDB_BIND_DN,
+ 'PASSWORD': settings.LDAPDB_BIND_PASSWORD,
+ 'SUPPORTS_TRANSACTIONS': False}
+connection = db.connections['ldap']
+
+# Add the LDAP router
+db.router.routers.append(Router())