handle renaming of LDAP entries
[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
28 import ldapdb
29 from ldapdb.models.query import QuerySet
30
31 class ModelBase(django.db.models.base.ModelBase):
32     """
33     Metaclass for all LDAP models.
34     """
35     def __new__(cls, name, bases, attrs):
36         attr_meta = attrs.pop('Ldap', None)
37
38         super_new = super(ModelBase, cls).__new__
39         new_class = super_new(cls, name, bases, attrs)
40
41         # patch manager to use our own QuerySet class
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         if attr_meta:
48             new_class._meta.dn = attr_meta.dn
49             new_class._meta.object_classes = attr_meta.object_classes
50
51         return new_class
52
53 class Model(django.db.models.base.Model):
54     """
55     Base class for all LDAP models.
56     """
57     __metaclass__ = ModelBase
58
59     def __init__(self, dn=None, *args, **kwargs):
60         self.dn = dn
61         super(Model, self).__init__(*args, **kwargs)
62         self.saved_pk = self.pk
63
64     def build_rdn(self):
65         """
66         Build the Relative Distinguished Name for this entry.
67         """
68         bits = []
69         for field in self._meta.local_fields:
70             if field.primary_key:
71                 bits.append("%s=%s" % (field.db_column, getattr(self, field.name)))
72         if not len(bits):
73             raise Exception("Could not build Distinguished Name")
74         return '+'.join(bits)
75
76     def build_dn(self):
77         """
78         Build the Distinguished Name for this entry.
79         """
80         return "%s,%s" % (self.build_rdn(), self._meta.dn)
81         raise Exception("Could not build Distinguished Name")
82
83     def delete(self):
84         """
85         Delete this entry.
86         """
87         logging.debug("Deleting LDAP entry %s" % self.dn)
88         ldapdb.connection.delete_s(self.dn)
89         
90     def save(self):
91         # create a new entry
92         if not self.dn:
93             entry = [('objectClass', self._meta.object_classes)]
94             new_dn = self.build_dn()
95
96             for field in self._meta.local_fields:
97                 if not field.db_column:
98                     continue
99                 value = getattr(self, field.name)
100                 if value:
101                     entry.append((field.db_column, value))
102
103             logging.debug("Creating new LDAP entry %s" % new_dn)
104             ldapdb.connection.add_s(new_dn, entry)
105             
106             # update object
107             self.dn = new_dn
108             self.saved_pk = self.pk
109             return
110
111         # update an existing entry
112         modlist = []
113         orig = self.__class__.objects.get(pk=self.saved_pk)
114         for field in self._meta.local_fields:
115             if not field.db_column:
116                 continue
117             old_value = getattr(orig, field.name, None)
118             new_value = getattr(self, field.name, None)
119             if old_value != new_value:
120                 if new_value:
121                     modlist.append((ldap.MOD_REPLACE, field.db_column, new_value))
122                 elif old_value:
123                     modlist.append((ldap.MOD_DELETE, field.db_column, None))
124
125         if not len(modlist):
126             logging.debug("No changes to be saved to LDAP entry %s" % self.dn)
127             return
128
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         self.saved_pk = self.pk
139