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/>.
21 # -*- coding: utf-8 -*-
26 import django.db.models
29 from ldapdb.models.query import QuerySet
31 class ModelBase(django.db.models.base.ModelBase):
33 Metaclass for all LDAP models.
35 def __new__(cls, name, bases, attrs):
36 attr_meta = attrs.pop('Ldap', None)
38 super_new = super(ModelBase, cls).__new__
39 new_class = super_new(cls, name, bases, attrs)
41 # patch manager to use our own QuerySet class
43 return QuerySet(new_class)
44 new_class.objects.get_query_set = get_query_set
45 new_class._default_manager.get_query_set = get_query_set
48 new_class._meta.dn = attr_meta.dn
49 new_class._meta.object_classes = attr_meta.object_classes
53 class Model(django.db.models.base.Model):
55 Base class for all LDAP models.
57 __metaclass__ = ModelBase
59 def __init__(self, dn=None, *args, **kwargs):
61 super(Model, self).__init__(*args, **kwargs)
65 Build the Distinguished Name for this entry.
67 for field in self._meta.local_fields:
69 return "%s=%s,%s" % (field.db_column, getattr(self, field.name), self._meta.dn)
70 raise Exception("Could not build Distinguished Name")
76 logging.debug("Deleting LDAP entry %s" % self.dn)
77 ldapdb.connection.delete_s(self.dn)
82 entry = [('objectClass', self._meta.object_classes)]
83 new_dn = self.build_dn()
85 for field in self._meta.local_fields:
86 if not field.db_column:
88 value = getattr(self, field.name)
90 entry.append((field.db_column, value))
92 logging.debug("Creating new LDAP entry %s" % new_dn)
93 ldapdb.connection.add_s(new_dn, entry)
99 # update an existing entry
101 orig = self.__class__.objects.get(pk=self.pk)
102 for field in self._meta.local_fields:
103 if not field.db_column:
105 old_value = getattr(orig, field.name, None)
106 new_value = getattr(self, field.name, None)
107 if old_value != new_value:
109 modlist.append((ldap.MOD_REPLACE, field.db_column, new_value))
111 modlist.append((ldap.MOD_DELETE, field.db_column, None))
114 logging.debug("Modifying existing LDAP entry %s" % self.dn)
115 ldapdb.connection.modify_s(self.dn, modlist)
117 logging.debug("No changes to be saved to LDAP entry %s" % self.dn)