models.py 6.61 KB
Newer Older
1
2
3
"""
Code used to access Debian's LDAP
"""
4
from django.utils.translation import gettext_lazy as _
5
from django.db import models
Enrico Zini's avatar
Enrico Zini committed
6
from django.urls import reverse
7
from django.forms.models import model_to_dict
8
from django.core.exceptions import ValidationError
9
from backend.models import Person, PersonAuditLog
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#  enrico> For people like Wookey, do you prefer we use only cn or only sn?
#          "sn" is used currently, and "cn" has a dash, but rather than
#          cargo-culting that in the new NM double check it with you
# @sgran> cn would be more usual
# @sgran> cn is the "whole name" and you can split it up into givenName + sn if you like
#  phil> Except that in Debian LDAP it isn't.
#  enrico> sgran: ok. should I use 'cn' for potential new cases then?
# @sgran> phil: indeed
# @sgran> but if we keep doing it the other way, we'll never be in a position to change
# @sgran> enrico: please
#  enrico> sgran: ack


24
25
26
27
28
29
30
31
32
33
34
35
36
37
class LDAPFieldsManager(models.Manager):
    def create(self, **kw):
        """
        Create a new process and all its requirements
        """
        audit_author = kw.pop("audit_author", None)
        audit_notes = kw.pop("audit_notes", None)
        audit_skip = kw.pop("audit_skip", False)

        obj = self.model(**kw)
        obj.save(using=self._db, audit_author=audit_author, audit_notes=audit_notes, audit_skip=audit_skip)
        return obj


38
39
40
41
42
43
class LDAPFields(models.Model):
    person = models.OneToOneField(Person, null=False, related_name="ldap_fields", on_delete=models.CASCADE)
    cn = models.CharField(_("first name"), max_length=250, null=False)
    mn = models.CharField(_("middle name"), max_length=250, null=False, blank=True, default="")
    sn = models.CharField(_("last name"), max_length=250, null=False, blank=True, default="")
    email = models.EmailField(_("LDAP forwarding email address"), null=False, blank=True)
Enrico Zini's avatar
Enrico Zini committed
44
    uid = models.CharField(_("Debian account name"), max_length=32, unique=True, null=True, blank=True)
45

46
47
    objects = LDAPFieldsManager()

48
    def __str__(self):
Enrico Zini's avatar
Enrico Zini committed
49
        return " ".join(x for x in (self.cn, self.mn, self.sn) if x) + f" <{self.uid}>"
50

Enrico Zini's avatar
Enrico Zini committed
51
    def get_absolute_url(self):
52
        return reverse("person:show", kwargs={"key": self.person.lookup_key})
Enrico Zini's avatar
Enrico Zini committed
53

54
    def clean_fields(self, exclude=None, *args, **kw):
Enrico Zini's avatar
Enrico Zini committed
55
        dam_forbidden_uids = (
56
57
58
59
60
            # standard system users
            "root", "daemon", "bin", "sys", "games", "man", "news", "uucp",
            "proxy", "www", "backup", "list", "irc", "gnats",
            # special Debian users
            "dsa", "dam", "dpl",
Enrico Zini's avatar
Enrico Zini committed
61
62
        )
        dsa_forbidden_uids = (
63
64
65
            # even if they are not taken, DSA doesn't like them
            "dns",
        )
66
67
        super().clean_fields(exclude=exclude, *args, **kw)
        if not exclude or "uid" not in exclude:
Enrico Zini's avatar
Enrico Zini committed
68
69
70
            if not self.uid:
                self.uid = None

71
72
            if self.uid and self.uid.endswith("-guest"):
                raise ValidationError({
73
                    "uid": _("UID must not end in '-guest'"),
74
75
76
                })
            if self.uid and len(self.uid) < 3:
                raise ValidationError({
77
                    "uid": _("UID must be at least 3 characters long"),
78
79
80
                })
            if self.uid and not self.uid.islower():
                raise ValidationError({
81
                    "uid": _("UID must consist only of only lowercase letters and digits"),
82
83
84
85
86
87
                })
            if self.uid and "." in self.uid:
                raise ValidationError({
                    "uid": _("DSA expressed a preference against dots in usernames."
                             " Contact debian-admin@lists.debian.org for details."),
                })
Mattia Rizzolo's avatar
Mattia Rizzolo committed
88
89
90
91
92
93
            # See RT#8583: - breaks the email address extension.
            if self.uid and "-" in self.uid:
                raise ValidationError({
                    "uid": _("DSA forbids dashes in usernames."
                             " Contact debian-admin@lists.debian.org for details."),
                })
Enrico Zini's avatar
Enrico Zini committed
94
95
            if self.uid and self.uid in dam_forbidden_uids:
                raise ValidationError({
96
                    "uid": _("The requested UID is a system user or a well known alias,"
Enrico Zini's avatar
Enrico Zini committed
97
98
99
                             " and cannot be used."),
                })
            if self.uid and self.uid in dsa_forbidden_uids:
100
                raise ValidationError({
101
                    "uid": _("The requested UID is not accepted by DSA."
Enrico Zini's avatar
Enrico Zini committed
102
                             " Contact debian-admin@lists.debian.org for details."),
103
                })
104

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    def save(self, *args, **kw):
        """
        Save, and add an entry to the Person audit log.

        Extra arguments that can be passed:

            audit_author: Person instance of the person doing the change
            audit_notes: free form text annotations for this change
            audit_skip: skip audit logging, used only for tests

        """
        # Extract our own arguments, so that they are not passed to django
        author = kw.pop("audit_author", None)
        notes = kw.pop("audit_notes", "")
        audit_skip = kw.pop("audit_skip", False)

        if audit_skip:
            changes = None
        else:
            # Get the previous version of the Person object, so that PersonAuditLog
            # can compute differences
            if self.pk:
                old_ldap_fields = LDAPFields.objects.get(pk=self.pk)
            else:
                old_ldap_fields = None

            changes = LDAPFields.diff(old_ldap_fields, self)
            if changes and not author:
                raise RuntimeError("Cannot save a LDAPFields instance without providing Author information")

        # Perform the save; if we are creating a new person, this will also
        # fill in the id/pk field, so that PersonAuditLog can link to us
        super().save(*args, **kw)

        # Finally, create the audit log entry
        if changes:
            PersonAuditLog.objects.create(
                    person=self.person, author=author, notes=notes, changes=PersonAuditLog.serialize_changes(changes))

    @classmethod
    def diff(cls, old_obj: "LDAPFields", new_obj: "LDAPFields"):
        """
        Compute the changes between two different instances of a Person model
        """
        changes = {}
        if old_obj is None:
            for k, nv in list(model_to_dict(new_obj).items()):
                changes[k] = [None, nv]
        else:
            old = model_to_dict(old_obj)
            new = model_to_dict(new_obj)
            for k, nv in list(new.items()):
                ov = old.get(k, None)
                # Also ignore changes like None -> ""
                if ov != nv and (ov or nv):
                    changes[k] = [ov, nv]
        return changes