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