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 BaseDatabaseOperations
26 def convert(field, value, func):
27 if not value or field == 'jpegPhoto':
29 elif isinstance(value, int):
31 elif isinstance(value, list):
32 return [ func(x) for x in value ]
36 def escape_ldap_filter(value):
38 return value.replace('\\', '\\5c') \
39 .replace('*', '\\2a') \
40 .replace('(', '\\28') \
41 .replace(')', '\\29') \
42 .replace('\0', '\\00')
44 class DatabaseOperations(BaseDatabaseOperations):
45 def quote_name(self, name):
48 class LdapConnection(object):
49 def __init__(self, server, bind_dn, bind_password):
50 self.connection = ldap.initialize(server)
51 self.connection.simple_bind_s(bind_dn, bind_password)
52 self.charset = "utf-8"
53 self.ops = DatabaseOperations()
55 def add_s(self, dn, modlist):
57 for field, value in modlist:
58 converted = convert(field, value, lambda x: x.encode(self.charset))
59 if isinstance(converted, list):
60 mods.append((field, converted))
62 mods.append((field, [converted]))
63 return self.connection.add_s(dn.encode(self.charset), mods)
65 def delete_s(self, dn):
66 return self.connection.delete_s(dn.encode(self.charset))
68 def modify_s(self, dn, modlist):
70 for op, field, value in modlist:
71 mods.append((op, field, convert(field, value, lambda x: x.encode(self.charset))))
72 return self.connection.modify_s(dn.encode(self.charset), mods)
74 def rename_s(self, dn, newrdn):
75 return self.connection.rename_s(dn.encode(self.charset), newrdn.encode(self.charset))
77 def search_s(self, base, scope, filterstr, attrlist):
78 results = self.connection.search_s(base, scope, filterstr.encode(self.charset), attrlist)
80 for dn, attrs in results:
82 if field == "member" or field == "memberUid":
83 attrs[field] = convert(field, attrs[field], lambda x: x.decode(self.charset))
85 attrs[field] = convert(field, attrs[field][0], lambda x: x.decode(self.charset))
86 output.append((dn.decode(self.charset), attrs))
89 # FIXME: is this the right place to initialize the LDAP connection?
90 connection = LdapConnection(settings.LDAPDB_SERVER_URI,
91 settings.LDAPDB_BIND_DN,
92 settings.LDAPDB_BIND_PASSWORD)