1 # -*- coding: utf-8 -*-
4 # Copyright (C) 2009 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
25 def convert(field, value, func):
26 if not value or field == 'jpegPhoto':
28 elif isinstance(value, int):
30 elif isinstance(value, list):
31 return [ func(x) for x in value ]
35 class LdapConnection(object):
36 def __init__(self, server, bind_dn, bind_password):
37 self.connection = ldap.initialize(server)
38 self.connection.simple_bind_s(bind_dn, bind_password)
39 self.charset = "utf-8"
41 def add_s(self, dn, modlist):
43 for field, value in modlist:
44 converted = convert(field, value, lambda x: x.encode(self.charset))
45 if isinstance(converted, list):
46 mods.append((field, converted))
48 mods.append((field, [converted]))
49 return self.connection.add_s(dn.encode(self.charset), mods)
51 def delete_s(self, dn):
52 return self.connection.delete_s(dn)
54 def modify_s(self, dn, modlist):
56 for op, field, value in modlist:
57 mods.append((op, field, convert(field, value, lambda x: x.encode(self.charset))))
58 return self.connection.modify_s(dn.encode(self.charset), mods)
60 def rename_s(self, dn, newrdn):
61 return self.connection.rename_s(dn.encode(self.charset), newrdn.encode(self.charset))
63 def search_s(self, base, scope, filterstr, attrlist):
64 results = self.connection.search_s(base, scope, filterstr.encode(self.charset), attrlist)
66 for dn, attrs in results:
68 if field == "member" or field == "memberUid":
69 attrs[field] = convert(field, attrs[field], lambda x: x.decode(self.charset))
71 attrs[field] = convert(field, attrs[field][0], lambda x: x.decode(self.charset))
72 output.append((dn.decode(self.charset), attrs))
75 # FIXME: is this the right place to initialize the LDAP connection?
76 connection = LdapConnection(settings.LDAPDB_SERVER_URI,
77 settings.LDAPDB_BIND_DN,
78 settings.LDAPDB_BIND_PASSWORD)