1 # -*- coding: utf-8 -*-
4 # Copyright (C) 2009-2010 Bolloré telecom
5 # See AUTHORS file for a full list of contributors.
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 from django.conf import settings
24 from django.db.backends import BaseDatabaseFeatures, BaseDatabaseOperations
26 def escape_ldap_filter(value):
28 return value.replace('\\', '\\5c') \
29 .replace('*', '\\2a') \
30 .replace('(', '\\28') \
31 .replace(')', '\\29') \
32 .replace('\0', '\\00')
34 class DatabaseCursor(object):
35 def __init__(self, ldap_connection):
36 self.connection = ldap_connection
38 class DatabaseFeatures(BaseDatabaseFeatures):
41 class DatabaseOperations(BaseDatabaseOperations):
42 def quote_name(self, name):
45 class LdapConnection(object):
47 self.connection = None
48 self.charset = "utf-8"
49 self.features = DatabaseFeatures()
50 self.ops = DatabaseOperations()
53 if self.connection is None:
54 self.connection = ldap.initialize(settings.LDAPDB_SERVER_URI)
55 self.connection.simple_bind_s(
56 settings.LDAPDB_BIND_DN,
57 settings.LDAPDB_BIND_PASSWORD)
58 return DatabaseCursor(self.connection)
60 def add_s(self, dn, modlist):
61 cursor = self._cursor()
62 return cursor.connection.add_s(dn.encode(self.charset), modlist)
64 def delete_s(self, dn):
65 cursor = self._cursor()
66 return cursor.connection.delete_s(dn.encode(self.charset))
68 def modify_s(self, dn, modlist):
69 cursor = self._cursor()
70 return cursor.connection.modify_s(dn.encode(self.charset), modlist)
72 def rename_s(self, dn, newrdn):
73 cursor = self._cursor()
74 return cursor.connection.rename_s(dn.encode(self.charset), newrdn.encode(self.charset))
76 def search_s(self, base, scope, filterstr, attrlist):
77 cursor = self._cursor()
78 results = cursor.connection.search_s(base, scope, filterstr.encode(self.charset), attrlist)
80 for dn, attrs in results:
81 output.append((dn.decode(self.charset), attrs))
84 # FIXME: is this the right place to initialize the LDAP connection?
85 connection = LdapConnection()