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