prune old stuff
[matthijs/upstream/django-ldapdb.git] / ldapdb / models / base.py
1 # -*- coding: utf-8 -*-
2
3 # django-ldapdb
4 # Copyright (C) 2009 BollorĂ© telecom
5 # See AUTHORS file for a full list of contributors.
6
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.
11
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.
16
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/>.
19 #
20
21 # -*- coding: utf-8 -*-
22
23 import ldap
24 import logging
25
26 import django.db.models
27 from django.db.models import signals
28
29 import ldapdb
30 from ldapdb.models.query import QuerySet
31
32 class ModelBase(django.db.models.base.ModelBase):
33     """
34     Metaclass for all LDAP models.
35     """
36     def __new__(cls, name, bases, attrs):
37         super_new = super(ModelBase, cls).__new__
38         new_class = super_new(cls, name, bases, attrs)
39
40         # patch manager to use our own QuerySet class
41         if not new_class._meta.abstract:
42             def get_query_set():
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
46
47         return new_class
48
49 class Model(django.db.models.base.Model):
50     """
51     Base class for all LDAP models.
52     """
53     __metaclass__ = ModelBase
54
55     dn = django.db.models.fields.CharField(max_length=200)
56
57     # meta-data
58     base_dn = None
59     object_classes = ['top']
60
61     def __init__(self, *args, **kwargs):
62         super(Model, self).__init__(*args, **kwargs)
63         self.saved_pk = self.pk
64
65     def build_rdn(self):
66         """
67         Build the Relative Distinguished Name for this entry.
68         """
69         bits = []
70         for field in self._meta.local_fields:
71             if field.primary_key:
72                 bits.append("%s=%s" % (field.db_column, getattr(self, field.name)))
73         if not len(bits):
74             raise Exception("Could not build Distinguished Name")
75         return '+'.join(bits)
76
77     def build_dn(self):
78         """
79         Build the Distinguished Name for this entry.
80         """
81         return "%s,%s" % (self.build_rdn(), self.base_dn)
82         raise Exception("Could not build Distinguished Name")
83
84     def delete(self):
85         """
86         Delete this entry.
87         """
88         logging.debug("Deleting LDAP entry %s" % self.dn)
89         ldapdb.connection.delete_s(self.dn)
90         signals.post_delete.send(sender=self.__class__, instance=self)
91         
92     def save(self):
93         if not self.dn:
94             # create a new entry
95             record_exists = False 
96             entry = [('objectClass', self.object_classes)]
97             new_dn = self.build_dn()
98
99             for field in self._meta.local_fields:
100                 if not field.db_column:
101                     continue
102                 value = getattr(self, field.name)
103                 if value:
104                     entry.append((field.db_column, value))
105
106             logging.debug("Creating new LDAP entry %s" % new_dn)
107             ldapdb.connection.add_s(new_dn, entry)
108
109             # update object
110             self.dn = new_dn
111
112         else:
113             # update an existing entry
114             record_exists = True
115             modlist = []
116             orig = self.__class__.objects.get(pk=self.saved_pk)
117             for field in self._meta.local_fields:
118                 if not field.db_column:
119                     continue
120                 old_value = getattr(orig, field.name, None)
121                 new_value = getattr(self, field.name, None)
122                 if old_value != new_value:
123                     if new_value:
124                         modlist.append((ldap.MOD_REPLACE, field.db_column, new_value))
125                     elif old_value:
126                         modlist.append((ldap.MOD_DELETE, field.db_column, None))
127
128             if len(modlist):
129                 # handle renaming
130                 new_dn = self.build_dn()
131                 if new_dn != self.dn:
132                     logging.debug("Renaming LDAP entry %s to %s" % (self.dn, new_dn))
133                     ldapdb.connection.rename_s(self.dn, self.build_rdn())
134                     self.dn = new_dn
135             
136                 logging.debug("Modifying existing LDAP entry %s" % self.dn)
137                 ldapdb.connection.modify_s(self.dn, modlist)
138             else:
139                 logging.debug("No changes to be saved to LDAP entry %s" % self.dn)
140
141         # done
142         self.saved_pk = self.pk
143         signals.post_save.send(sender=self.__class__, instance=self, created=(not record_exists))
144
145     @classmethod
146     def scoped(base_class, base_dn):
147         """
148         Returns a copy of the current class with a different base_dn.
149         """
150         import new
151         import re
152         suffix = re.sub('[=,]', '_', base_dn)
153         name = "%s_%s" % (base_class.__name__, str(suffix))
154         new_class = new.classobj(name, (base_class,), {'base_dn': base_dn, '__module__': base_class.__module__})
155         return new_class
156