models.py 30.9 KB
Newer Older
1
2
3
"""
Core models of the New Member site
"""
Enrico Zini's avatar
Enrico Zini committed
4
from __future__ import annotations
5
from django.utils.translation import gettext_lazy as _
6
from django.core.exceptions import ObjectDoesNotExist
7
from django.utils.timezone import now
8
from django.db import models
Enrico Zini's avatar
Enrico Zini committed
9
from django.conf import settings
10
from django.urls import reverse
Enrico Zini's avatar
Enrico Zini committed
11
from django.contrib.auth.models import BaseUserManager, PermissionsMixin
12
from django.forms.models import model_to_dict
13
14

from keyring import utils as kutils
15
from . import const
16
from . import permissions
17
from .fields import FingerprintField
18
from .utils import cached_property
19
import datetime
Enrico Zini's avatar
Enrico Zini committed
20
21
22
import urllib.request
import urllib.parse
import urllib.error
Enrico Zini's avatar
Enrico Zini committed
23
import re
24
import json
25

26
DM_IMPORT_DATE = getattr(settings, "DM_IMPORT_DATE", None)
Enrico Zini's avatar
Enrico Zini committed
27

28

Enrico Zini's avatar
Enrico Zini committed
29
30
31
32
class PersonManager(BaseUserManager):
    def create_user(self, email, **other_fields):
        if not email:
            raise ValueError('Users must have an email address')
33
34
35
        audit_author = other_fields.pop("audit_author", None)
        audit_notes = other_fields.pop("audit_notes", None)
        audit_skip = other_fields.pop("audit_skip", False)
36
        fpr = other_fields.pop("fpr", None)
37
38
39
40
41
42
43
        ldap_fields = {
            "cn": other_fields.pop("cn", None),
            "mn": other_fields.pop("mn", None),
            "sn": other_fields.pop("sn", None),
            "uid": other_fields.pop("uid", None),
            "email": other_fields.pop("email_ldap", email),
        }
44
45
        if "fullname" not in other_fields:
            other_fields["fullname"] = _build_fullname(
46
                ldap_fields["cn"], ldap_fields["mn"], ldap_fields["sn"])
Enrico Zini's avatar
Enrico Zini committed
47
48
49
50
        user = self.model(
            email=self.normalize_email(email),
            **other_fields
        )
51
        user.save(using=self._db, audit_author=audit_author, audit_notes=audit_notes, audit_skip=audit_skip)
52
        if fpr:
Enrico Zini's avatar
Enrico Zini committed
53
            Fingerprint.objects.create(fpr=fpr, person=user, is_active=True,
54
55
56
                                       audit_author=audit_author,
                                       audit_notes=audit_notes,
                                       audit_skip=audit_skip)
57
58
59
60
61
62
63
64
65
66
        if ldap_fields["uid"]:
            from dsa.models import LDAPFields
            LDAPFields.objects.create(
                person=user,
                audit_author=audit_author,
                audit_notes=audit_notes,
                audit_skip=audit_skip,
                **ldap_fields
            )

Enrico Zini's avatar
Enrico Zini committed
67
68
69
70
        return user

    def create_superuser(self, email, **other_fields):
        other_fields["is_superuser"] = True
71
        other_fields["is_staff"] = True
Enrico Zini's avatar
Enrico Zini committed
72
73
        return self.create_user(email, **other_fields)

74
75
76
77
78
79
80
81
82
83
    def get_or_none(self, *args, **kw):
        """
        Same as get(), but returns None instead of raising DoesNotExist if the
        object cannot be found
        """
        try:
            return self.get(*args, **kw)
        except self.model.DoesNotExist:
            return None

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    def get_housekeeper(self):
        """
        Return the housekeeping person, creating it if it does not exist yet
        """
        # Ensure that there is a __housekeeping__ user
        try:
            return self.get(email="nm@debian.org")
        except self.model.DoesNotExist:
            from dsa.models import LDAPFields
            res = self.create_user(
                is_staff=False,
                fullname="nm.debian.org Housekeeping Robot",
                email="nm@debian.org",
                bio="I am the robot that runs the automated tasks in the site",
                status=const.STATUS_DC,
                audit_skip=True)
            LDAPFields.objects.create(person=res, audit_skip=True)
            return res

Enrico Zini's avatar
Enrico Zini committed
103
    def get_from_other_db(
104
            self, other_db_name, uid=None, email=None, fpr=None, format_person=lambda x: str(x)):
105
        """
106
        Get one Person entry matching the information that another database
107
108
        has about a person.

109
        One or more of uid, email, or fpr must be provided, and the
110
111
112
113
114
115
116
117
118
119
120
        function will ensure consistency in the results. That is, only one
        person will be returned, and it will raise an exception if the data
        provided match different Person entries in our database.

        other_db_name is the name of the database where the parameters come
        from, to use in generating exception messages.

        It returns None if nothing is matched.
        """
        candidates = []
        if uid is not None:
Enrico Zini's avatar
Enrico Zini committed
121
            p = self.get_or_none(ldap_fields__uid=uid)
122
123
124
125
126
127
128
            if p is not None:
                candidates.append((p, "uid", uid))
        if email is not None:
            p = self.get_or_none(email=email)
            if p is not None:
                candidates.append((p, "email", email))
        if fpr is not None:
129
            p = self.get_or_none(fprs__fpr=fpr)
130
131
132
133
134
135
136
137
138
139
140
141
142
            if p is not None:
                candidates.append((p, "fingerprint", fpr))

        # No candidates, nothing was found
        if not candidates:
            return None

        candidate = candidates[0]

        # Check for conflicts in the database
        for person, match_type, match_value in candidates[1:]:
            if candidate[0].pk != person.pk:
                raise self.model.MultipleObjectsReturned(
Enrico Zini's avatar
Enrico Zini committed
143
144
                    "{} has {} {}, which corresponds to two different users in our db: "
                    "{} (by {} {}) and {} (by {} {})".format(
145
146
147
148
149
150
                        other_db_name, match_type, match_value,
                        format_person(candidate[0]), candidate[1], candidate[2],
                        format_person(person), match_type, match_value))

        return candidate[0]

Enrico Zini's avatar
Enrico Zini committed
151

152
153
154
155
156
157
158
159
160
161
162
163
164
def _build_fullname(cn, mn, sn):
    if not mn:
        if not sn:
            return cn
        else:
            return "{} {}".format(cn, sn)
    else:
        if not sn:
            return "{} {}".format(cn, mn)
        else:
            return "{} {} {}".format(cn, mn, sn)


Enrico Zini's avatar
Enrico Zini committed
165
class Person(PermissionsMixin, models.Model):
166
167
168
169
170
    """
    A person (DM, DD, AM, applicant, FD member, DAM, anything)
    """
    class Meta:
        db_table = "person"
171
        ordering = ("fullname",)
172

Enrico Zini's avatar
Enrico Zini committed
173
174
    objects = PersonManager()

175
    # Standard Django user fields
Enrico Zini's avatar
Enrico Zini committed
176
177
178
    last_login = models.DateTimeField(_('last login'), default=now)
    date_joined = models.DateTimeField(_('date joined'), default=now)
    is_staff = models.BooleanField(default=False)
Enrico Zini's avatar
Enrico Zini committed
179
    # is_active = True
180
    fullname = models.CharField(_("full name"), max_length=255)
Enrico Zini's avatar
Enrico Zini committed
181
182
183

    #  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
Enrico Zini's avatar
Enrico Zini committed
184
    #          cargo-culting that in the new NM double check it with you
Enrico Zini's avatar
Enrico Zini committed
185
186
187
188
189
190
191
192
193
    # @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

194
195
    # Most user fields mirror Debian LDAP fields

Enrico Zini's avatar
Enrico Zini committed
196
    # First/Given name, or only name in case of only one name
197
    email = models.EmailField(_("email address"), null=False, unique=True)
Mattia Rizzolo's avatar
Mattia Rizzolo committed
198
199
200
201
    bio = models.TextField(
        _("short biography"), blank=True, null=False, default="",
        help_text=_("The short biography may be visible on this site and published to a mailing list")
    )
202
203

    # Membership status
204
    status = models.CharField(_("current status in the project"), max_length=20, null=False,
205
                              choices=[(x.tag, x.ldesc) for x in const.ALL_STATUS])
206
207
    status_changed = models.DateTimeField(_("when the status last changed"), null=False, default=now)
    fd_comment = models.TextField(_("Front Desk comments"), null=False, blank=True, default="")
Enrico Zini's avatar
Enrico Zini committed
208
    # null=True because we currently do not have the info for old entries
209
    created = models.DateTimeField(_("Person record created"), null=True, default=now)
Enrico Zini's avatar
Enrico Zini committed
210
211
    expires = models.DateField(
            _("Expiration date for the account"), null=True, blank=True, default=None,
212
            help_text=_("This person will be deleted after this date if the status is still {} and"
Enrico Zini's avatar
Enrico Zini committed
213
                        " no Process has started").format(const.STATUS_DC))
214
    pending = models.CharField(_("Nonce used to confirm this pending record"), max_length=255, unique=False, blank=True)
215
    last_vote = models.DateField(null=True, blank=True, help_text=_("date of the last vote done with this UID"))
216

Enrico Zini's avatar
Enrico Zini committed
217
218
219
220
    status_description = models.CharField(
            max_length=128, null=False, blank=True,
            help_text=_("Override for the status description for when the default is not enough"))

Enrico Zini's avatar
Enrico Zini committed
221
222
223
224
    def get_full_name(self):
        return self.fullname

    def get_short_name(self):
225
        return self.ldap_fields.cn
Enrico Zini's avatar
Enrico Zini committed
226
227

    def get_username(self):
228
        return self.email
Enrico Zini's avatar
Enrico Zini committed
229

Enrico Zini's avatar
Enrico Zini committed
230
    @property
Enrico Zini's avatar
Enrico Zini committed
231
232
233
    def is_anonymous(self):
        return False

Enrico Zini's avatar
Enrico Zini committed
234
    @property
Enrico Zini's avatar
Enrico Zini committed
235
236
237
    def is_authenticated(self):
        return True

Enrico Zini's avatar
Enrico Zini committed
238
239
240
    def is_active(self):
        return True

Enrico Zini's avatar
Enrico Zini committed
241
242
243
244
245
246
247
248
249
250
251
252
    def set_password(self, raw_password):
        pass

    def check_password(self, raw_password):
        return False

    def set_unusable_password(self):
        pass

    def has_usable_password(self):
        return False

253
254
255
256
257
258
259
260
261
262
263
264
265
    @property
    def fingerprint(self):
        """
        Return the Fingerprint associated to this person, or None if there is
        none
        """
        # If there is more than one active fingerprint, return a random one.
        # This should not happen, and a nightly maintenance task will warn if
        # it happens.
        for f in self.fprs.filter(is_active=True):
            return f
        return None

266
267
268
269
270
    @property
    def fpr(self):
        """
        Return the current fingerprint for this Person
        """
271
        f = self.fingerprint
Enrico Zini's avatar
Enrico Zini committed
272
273
        if f is not None:
            return f.fpr
274
275
        return None

276
    USERNAME_FIELD = 'email'
277
    REQUIRED_FIELDS = ["fullname", "status"]
Enrico Zini's avatar
Enrico Zini committed
278

279
280
281
282
283
284
285
    @property
    def person(self):
        """
        Allow to call foo.person to get a Person record, regardless if foo is a Person or an AM
        """
        return self

286
287
288
289
290
291
292
293
294
295
296
297
    @cached_property
    def perms(self):
        """
        Get permission tags for this user
        """
        res = set()
        is_dd = self.status in (const.STATUS_DD_U, const.STATUS_DD_NU)

        if is_dd:
            res.add("dd")
            am = self.am_or_none
            if am:
298
299
                if am.is_am:
                    res.add("am")
300
                if self.is_superuser:
301
302
                    res.add("am")
                    res.add("admin")
303
304
305
306
307
            else:
                res.add("am_candidate")

        return frozenset(res)

Enrico Zini's avatar
Enrico Zini committed
308
309
    @property
    def is_dd(self):
310
        return "dd" in self.perms
Enrico Zini's avatar
Enrico Zini committed
311

312
    @property
Enrico Zini's avatar
Enrico Zini committed
313
    def is_am(self):
314
        return "am" in self.perms
Enrico Zini's avatar
Enrico Zini committed
315

316
317
318
319
320
    def can_become_am(self):
        """
        Check if the person can become an AM
        """
        return "am_candidate" in self.perms
321

322
323
324
325
326
327
328
    @property
    def am_or_none(self):
        try:
            return self.am
        except AM.DoesNotExist:
            return None

329
330
    @property
    def changed_before_data_import(self):
331
        return DM_IMPORT_DATE is not None and self.status in (
Enrico Zini's avatar
Enrico Zini committed
332
                const.STATUS_DM, const.STATUS_DM_GA) and self.status_changed <= DM_IMPORT_DATE
333

Enrico Zini's avatar
Enrico Zini committed
334
    def permissions_of(self, visitor):
335
        """
Enrico Zini's avatar
Enrico Zini committed
336
        Compute which PersonVisitorPermissions the given person has over this person
337
        """
338
339
340
341
        if visitor.is_authenticated:
            return permissions.PersonVisitorPermissions(self, visitor)
        else:
            return permissions.PersonVisitorPermissions(self, None)
342

343
344
345
346
347
348
    @property
    def preferred_email(self):
        """
        Return uid@debian.org if the person is a DD, else return the email
        field.
        """
349
        if self.status in (const.STATUS_DD_U, const.STATUS_DD_NU):
350
            return "{}@debian.org".format(self.ldap_fields.uid)
351
352
353
        else:
            return self.email

Enrico Zini's avatar
Enrico Zini committed
354
    def __str__(self):
Enrico Zini's avatar
Enrico Zini committed
355
        return "{} <{}>".format(self.fullname, self.email)
356
357

    def __repr__(self):
358
        return "{} <{}> [uid:{}, status:{}]".format(
Enrico Zini's avatar
Enrico Zini committed
359
                self.fullname, self.email, self.get_ldap_uid(), self.status)
360

361
    def get_absolute_url(self):
362
        return reverse("person:show", kwargs=dict(key=self.lookup_key))
363

364
365
366
    def get_admin_url(self):
        return reverse("admin:backend_person_change", args=[self.pk])

367
368
369
370
371
372
373
374
375
    def get_picture_url(self):
        """
        Return a URL to a picture for the person, if available, else None
        """
        for identity in self.identities.all():
            if identity.picture:
                return identity.picture
        return None

376
377
378
379
380
381
    def get_ldap_uid(self):
        try:
            return self.ldap_fields.uid
        except ObjectDoesNotExist:
            return None

382
383
384
385
386
387
388
389
    @property
    def a_link(self):
        from django.utils.safestring import mark_safe
        from django.utils.html import conditional_escape
        return mark_safe("<a href='{}'>{}</a>".format(
            conditional_escape(self.get_absolute_url()),
            conditional_escape(self.lookup_key)))

Enrico Zini's avatar
Enrico Zini committed
390
    def get_ddpo_url(self):
Enrico Zini's avatar
Enrico Zini committed
391
        return "http://qa.debian.org/developer.php?{}".format(urllib.parse.urlencode(dict(login=self.preferred_email)))
Enrico Zini's avatar
Enrico Zini committed
392

Enrico Zini's avatar
Enrico Zini committed
393
    def get_portfolio_url(self):
Enrico Zini's avatar
Enrico Zini committed
394
        parms = dict(
395
            email=self.preferred_email,
396
            name=self.fullname,
Enrico Zini's avatar
Enrico Zini committed
397
398
399
400
401
402
403
404
            gpgfp="",
            username="",
            nonddemail=self.email,
            wikihomepage="",
            forumsid=""
        )
        if self.fpr:
            parms["gpgfp"] = self.fpr
405
406
        if self.get_ldap_uid():
            parms["username"] = self.get_ldap_uid()
Enrico Zini's avatar
Enrico Zini committed
407
        return "http://portfolio.debian.net/result?" + urllib.parse.urlencode(parms)
Enrico Zini's avatar
Enrico Zini committed
408

409
    def get_contributors_url(self):
410
        from signon.models import Identity
411
        if self.is_dd:
412
            return "https://contributors.debian.org/contributor/{}@debian".format(self.ldap_fields.uid)
413
414
415
416
417
418
419
420
421

        try:
            debsso = self.identities.get(issuer="debsso")
            if debsso.subject.endswith("@users.alioth.debian.org"):
                return "https://contributors.debian.org/contributor/{}@alioth".format(debsso.subject[:-24])
        except Identity.DoesNotExist:
            pass

        return None
422

423
424
425
    _new_status_table = {
        const.STATUS_DC: [const.STATUS_DC_GA, const.STATUS_DM, const.STATUS_DD_U, const.STATUS_DD_NU],
        const.STATUS_DC_GA: [const.STATUS_DM_GA, const.STATUS_DD_U, const.STATUS_DD_NU],
Enrico Zini's avatar
Enrico Zini committed
426
427
        const.STATUS_DM: [const.STATUS_DM_GA, const.STATUS_DD_NU, const.STATUS_DD_U],
        const.STATUS_DM_GA: [const.STATUS_DD_NU, const.STATUS_DD_U],
428
        const.STATUS_DD_NU: [const.STATUS_DD_U, const.STATUS_EMERITUS_DD],
429
        const.STATUS_DD_U: [const.STATUS_DD_NU, const.STATUS_EMERITUS_DD],
430
431
432
433
        const.STATUS_EMERITUS_DD: [const.STATUS_DD_U, const.STATUS_DD_NU],
        const.STATUS_REMOVED_DD: [const.STATUS_DD_U, const.STATUS_DD_NU],
    }

434
    @property
435
436
437
438
439
    def possible_new_statuses(self):
        """
        Return a list of possible new statuses that can be requested for the
        person
        """
Enrico Zini's avatar
Enrico Zini committed
440
441
        if self.pending:
            return []
442

443
        statuses = list(self._new_status_table.get(self.status, []))
Enrico Zini's avatar
Enrico Zini committed
444

445
        # Compute statuses one is already applying for in active processes
446
        blacklist = []
447
448
        if statuses:
            import process.models as pmodels
449
            for proc in pmodels.Process.objects.filter(person=self, closed_time__isnull=True):
450
                blacklist.append(proc.applying_for)
Enrico Zini's avatar
Enrico Zini committed
451
452
453
454
        if const.STATUS_DD_U in blacklist:
            blacklist.append(const.STATUS_DD_NU)
        if const.STATUS_DD_NU in blacklist:
            blacklist.append(const.STATUS_DD_U)
455
456
457
        if const.STATUS_EMERITUS_DD in blacklist:
            blacklist.append(const.STATUS_REMOVED_DD)
            blacklist.append(const.STATUS_DD_U)
458
            blacklist.append(const.STATUS_DD_NU)
459
460
        if const.STATUS_REMOVED_DD in blacklist:
            blacklist.append(const.STATUS_EMERITUS_DD)
461
462
            blacklist.append(const.STATUS_DD_U)
            blacklist.append(const.STATUS_DD_NU)
Enrico Zini's avatar
Enrico Zini committed
463

464
        for status in blacklist:
Enrico Zini's avatar
Enrico Zini committed
465
466
467
468
469
            try:
                statuses.remove(status)
            except ValueError:
                pass

470
471
        return statuses

472
473
474
475
476
477
    def make_pending(self, days_valid=30):
        """
        Make this person a pending person.

        It does not automatically save the Person.
        """
478
        from django.utils.crypto import get_random_string
479
480
481
        self.pending = get_random_string(length=12,
                                         allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                         'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
482
483
        self.expires = now().date() + datetime.timedelta(days=days_valid)

484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    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_person = Person.objects.get(pk=self.pk)
            else:
                old_person = None

510
            changes = Person.diff(old_person, self)
511
512
513
514
515
516
517
518
519
            if changes and not author:
                raise RuntimeError("Cannot save a Person 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(Person, self).save(*args, **kw)

        # Finally, create the audit log entry
        if changes:
Enrico Zini's avatar
Enrico Zini committed
520
521
            PersonAuditLog.objects.create(
                    person=self, author=author, notes=notes, changes=PersonAuditLog.serialize_changes(changes))
522

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    @classmethod
    def diff(cls, old_person: "Person", new_person: "Person"):
        """
        Compute the changes between two different instances of a Person model
        """
        exclude = ["last_login", "date_joined", "groups", "user_permissions"]
        changes = {}
        if old_person is None:
            for k, nv in list(model_to_dict(new_person, exclude=exclude).items()):
                changes[k] = [None, nv]
        else:
            old = model_to_dict(old_person, exclude=exclude)
            new = model_to_dict(new_person, exclude=exclude)
            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

543
544
545
546
547
548
549
550
    @property
    def lookup_key(self):
        """
        Return a key that can be used to look up this person in the database
        using Person.lookup.

        Currently, this is the uid if available, else the email.
        """
551
552
553
        uid = self.get_ldap_uid()
        if uid:
            return uid
554
        elif self.email:
555
            return self.email
556
557
        else:
            return self.fpr
558
559
560

    @classmethod
    def lookup(cls, key):
561
562
563
        try:
            if "@" in key:
                return cls.objects.get(email=key)
564
            elif re.match(r"^[0-9A-Fa-f]{32,40}$", key):
565
                return cls.objects.get(fprs__fpr=key.upper())
566
            else:
567
                return cls.objects.get(ldap_fields__uid=key)
568
569
        except cls.DoesNotExist:
            return None
570

571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
    @classmethod
    def lookup_by_email(cls, addr):
        """
        Return the person corresponding to an email address, or None if no such
        person has been found.
        """
        try:
            return cls.objects.get(email=addr)
        except cls.DoesNotExist:
            pass
        if not addr.endswith("@debian.org"):
            return None
        try:
            return cls.objects.get(uid=addr[:-11])
        except cls.DoesNotExist:
            return None

588
589
590
591
592
593
594
    @classmethod
    def lookup_or_404(cls, key):
        from django.http import Http404
        res = cls.lookup(key)
        if res is not None:
            return res
        raise Http404
595

596

Enrico Zini's avatar
Enrico Zini committed
597
class FingerprintManager(BaseUserManager):
598
    def create(self, **fields):
Enrico Zini's avatar
Enrico Zini committed
599
600
601
        audit_author = fields.pop("audit_author", None)
        audit_notes = fields.pop("audit_notes", None)
        audit_skip = fields.pop("audit_skip", False)
Enrico Zini's avatar
Enrico Zini committed
602
        fields["fpr"] = fields["fpr"].replace(" ", "")
Enrico Zini's avatar
Enrico Zini committed
603
604
605
606
607
        res = self.model(**fields)
        res.save(using=self._db, audit_author=audit_author, audit_notes=audit_notes, audit_skip=audit_skip)
        return res


Enrico Zini's avatar
Enrico Zini committed
608
609
610
611
612
613
614
class Fingerprint(models.Model):
    """
    A fingerprint for a person
    """
    class Meta:
        db_table = "fingerprints"

Enrico Zini's avatar
Enrico Zini committed
615
616
    objects = FingerprintManager()

Enrico Zini's avatar
Enrico Zini committed
617
    person = models.ForeignKey(Person, related_name="fprs", on_delete=models.CASCADE)
618
    fpr = FingerprintField(verbose_name=_("OpenPGP key fingerprint"), max_length=40, unique=True)
619
    is_active = models.BooleanField(default=False, help_text=_("whether this key is currently in use"))
Enrico Zini's avatar
Enrico Zini committed
620
621
    last_upload = models.DateField(
            null=True, blank=True, help_text=_("date of the last ftp-master upload done with this key"))
Enrico Zini's avatar
Enrico Zini committed
622

Enrico Zini's avatar
Enrico Zini committed
623
    def __str__(self):
624
625
        return self.fpr

626
627
628
629
    def get_key(self):
        from keyring.models import Key
        return Key.objects.get_or_download(self.fpr)

630
631
632
    def get_absolute_url(self):
        return reverse("fprs:view_endorsements", kwargs=dict(fpr=self.fpr, key=self.person.lookup_key))

Enrico Zini's avatar
Enrico Zini committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    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 Fingerprint object, so that
            # PersonAuditLog can compute differences
            if self.pk:
                existing_fingerprint = Fingerprint.objects.get(pk=self.pk)
            else:
                existing_fingerprint = None

            changes = PersonAuditLog.diff_fingerprint(existing_fingerprint, self)
            if changes and not author:
661
                raise RuntimeError("Cannot save a Fingerprint instance without providing Author information")
Enrico Zini's avatar
Enrico Zini committed
662
663
664
665
666
667
668

        # 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(Fingerprint, self).save(*args, **kw)

        # Finally, create the audit log entry
        if changes:
669
            if existing_fingerprint is not None and existing_fingerprint.person.pk != self.person.pk:
Enrico Zini's avatar
Enrico Zini committed
670
671
672
673
674
                PersonAuditLog.objects.create(
                        person=existing_fingerprint.person, author=author, notes=notes,
                        changes=PersonAuditLog.serialize_changes(changes))
            PersonAuditLog.objects.create(
                    person=self.person, author=author, notes=notes, changes=PersonAuditLog.serialize_changes(changes))
Enrico Zini's avatar
Enrico Zini committed
675

676
677
678
679
680
681
        # If we are saving an active fingerprint, make all others inactive
        if self.is_active:
            for fpr in Fingerprint.objects.filter(person=self.person, is_active=True).exclude(pk=self.pk):
                fpr.is_active = False
                fpr.save(audit_notes=notes, audit_author=author, audit_skip=audit_skip)

Enrico Zini's avatar
Enrico Zini committed
682

683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
class FingerprintEndorsement(models.Model):
    """Class representing the endorsement from a user for a Key"""
    fingerprint = models.ForeignKey(
        Fingerprint,
        related_name="received_endorsements",
        related_query_name="received_endorsement",
        null=False,
        on_delete=models.CASCADE
    )
    author = models.ForeignKey(
        Person,
        related_name="emitted_endorsements",
        related_query_name="emitted_endorsement",
        null=False,
        on_delete=models.CASCADE,
    )
Enrico Zini's avatar
Enrico Zini committed
699
700
701
702
703
704
    endorsing_fpr = models.ForeignKey(
        Fingerprint,
        related_name="+",
        null=False,
        on_delete=models.CASCADE,
        help_text=_("Fingerprint used to verify the endorsement"))
705
706
707
708
709
710
711
712
    date = models.DateTimeField(null=False, default=now)
    text = models.TextField(null=False, blank=False)

    @property
    def text_clean(self):
        """
        Return the statement without the OpenPGP wrapping
        """
713
        return kutils.cleaned_text(self.text).strip()
714
715
716
717
718
719
720
721
722

    @property
    def rfc3156(self):
        """
        If the statement is an email, parse it as rfc3156, else return None
        """
        return kutils.rfc3156(self.text)

    def get_absolute_url(self):
Enrico Zini's avatar
Enrico Zini committed
723
724
725
726
        return reverse("fprs:view_endorsements", kwargs={
            "fpr": self.fingerprint.fpr,
            "key": self.fingerprint.person.lookup_key
        })
727
728


729
class PersonAuditLog(models.Model):
Enrico Zini's avatar
Enrico Zini committed
730
    person = models.ForeignKey(Person, related_name="audit_log", on_delete=models.CASCADE)
731
    logdate = models.DateTimeField(null=False, auto_now_add=True)
Enrico Zini's avatar
Enrico Zini committed
732
    author = models.ForeignKey(Person, related_name="+", null=False, on_delete=models.CASCADE)
733
734
735
    notes = models.TextField(null=False, default="")
    changes = models.TextField(null=False, default="{}")

736
    def __str__(self):
Enrico Zini's avatar
Enrico Zini committed
737
738
        return "{:%Y-%m-%d %H:%S}:{}: {}:{}".format(
                self.logdate, self.person.lookup_key, self.author.lookup_key, self.notes)
739

Enrico Zini's avatar
Enrico Zini committed
740
741
742
743
744
745
746
747
    @classmethod
    def diff_fingerprint(cls, existing_fpr, new_fpr):
        """
        Compute the changes between two different instances of a Fingerprint model
        """
        exclude = []
        changes = {}
        if existing_fpr is None:
Enrico Zini's avatar
Enrico Zini committed
748
            for k, nv in list(model_to_dict(new_fpr, exclude=exclude).items()):
Enrico Zini's avatar
Enrico Zini committed
749
750
751
752
                changes["fpr:{}:{}".format(new_fpr.fpr, k)] = [None, nv]
        else:
            old = model_to_dict(existing_fpr, exclude=exclude)
            new = model_to_dict(new_fpr, exclude=exclude)
Enrico Zini's avatar
Enrico Zini committed
753
            for k, nv in list(new.items()):
Enrico Zini's avatar
Enrico Zini committed
754
755
756
                ov = old.get(k, None)
                # Also ignore changes like None -> ""
                if ov != nv and (ov or nv):
757
                    changes["fpr:{}:{}".format(existing_fpr.fpr, k)] = [ov, nv]
Enrico Zini's avatar
Enrico Zini committed
758
759
        return changes

760
761
762
763
764
765
766
767
768
769
770
771
772
    @classmethod
    def serialize_changes(cls, changes):
        class Serializer(json.JSONEncoder):
            def default(self, o):
                if isinstance(o, datetime.datetime):
                    return o.strftime("%Y-%m-%d %H:%M:%S")
                elif isinstance(o, datetime.date):
                    return o.strftime("%Y-%m-%d")
                else:
                    return json.JSONEncoder.default(self, o)
        return json.dumps(changes, cls=Serializer)


773
774
775
776
777
778
779
class AM(models.Model):
    """
    Extra info for people who are or have been AMs, FD members, or DAMs
    """
    class Meta:
        db_table = "am"

Enrico Zini's avatar
Enrico Zini committed
780
    person = models.OneToOneField(Person, related_name="am", on_delete=models.CASCADE)
781
    slots = models.IntegerField(null=False, default=1)
782
783
784
    is_am = models.BooleanField(_("Active AM"), null=False, default=True)
    is_fd = models.BooleanField(_("FD member"), null=False, default=False)
    is_dam = models.BooleanField(_("DAM"), null=False, default=False)
785
786
    # Automatically computed as true if any applicant was approved in the last
    # 6 months
787
    is_am_ctte = models.BooleanField(_("NM CTTE member"), null=False, default=False)
Enrico Zini's avatar
Enrico Zini committed
788
    # null=True because we currently do not have the info for old entries
789
790
    created = models.DateTimeField(_("AM record created"), null=True, default=now)
    fd_comment = models.TextField(_("Front Desk comments"), null=False, blank=True, default="")
791

Enrico Zini's avatar
Enrico Zini committed
792
    def __str__(self):
Enrico Zini's avatar
Enrico Zini committed
793
794
        return "%s %c%c%c" % (
            str(self.person),
Enrico Zini's avatar
Enrico Zini committed
795
796
797
798
799
            "a" if self.is_am else "-",
            "f" if self.is_fd else "-",
            "d" if self.is_dam else "-",
        )

800
801
802
803
804
805
806
807
    def __repr__(self):
        return "%s %c%c%c slots:%d" % (
            repr(self.person),
            "a" if self.is_am else "-",
            "f" if self.is_fd else "-",
            "d" if self.is_dam else "-",
            self.slots)

808
    def get_absolute_url(self):
809
        return reverse("person:show", kwargs=dict(key=self.person.lookup_key))
810

Enrico Zini's avatar
Enrico Zini committed
811
    @classmethod
812
    def list_available(cls, free_only=False):
Enrico Zini's avatar
Enrico Zini committed
813
814
815
816
817
818
        """
        Get a list of active AMs with free slots, ordered by uid.

        Each AM is annotated with stats_active, stats_held and stats_free, with
        the number of NMs, held NMs and free slots.
        """
819
        import process.models as pmodels
Enrico Zini's avatar
Enrico Zini committed
820

821
        ams = {}
822
        for am in AM.objects.all():
823
824
825
826
            am.proc_active = []
            am.proc_held = []
            ams[am] = am

827
        # loop through open processes and collect the AM status of each
Enrico Zini's avatar
Enrico Zini committed
828
        for p in pmodels.AMAssignment.objects.filter(
829
                    # The process is not frozen or approved
830
831
                    process__frozen_by__isnull=True,
                    process__approved_by__isnull=True,
832
                    # The process is still open
833
834
835
                    process__closed_time__isnull=True,
                    # The AM hasn't been unassigned
                    unassigned_by__isnull=True,
836
837
838
839
                    # The AM report requirement is not approved yet
                    # (if it is, the AM is no longer active on that assignement)
                    process__requirements__type='am_ok',
                    process__requirements__approved_time__isnull=True,
840
                ).select_related("am"):
841
842
843
844
845
            am = ams[p.am]
            if p.paused:
                am.proc_held.append(p)
            else:
                am.proc_active.append(p)
846

847
        res = []
Enrico Zini's avatar
Enrico Zini committed
848
        for am in list(ams.values()):
849
850
            am.stats_active = len(am.proc_active)
            am.stats_held = len(am.proc_held)
851
852
853
            am.stats_free = am.slots - am.stats_active

            if free_only and am.stats_free <= 0:
Enrico Zini's avatar
Enrico Zini committed
854
                continue
855
856

            res.append(am)
857
        res.sort(key=lambda x: (-x.stats_free, x.stats_active))
Enrico Zini's avatar
Enrico Zini committed
858
859
        return res

860
861
862
863
864
865
866
867
868
869
870
871
872
    @property
    def lookup_key(self):
        """
        Return a key that can be used to look up this manager in the database
        using AM.lookup.

        Currently, this is the lookup key of the person.
        """
        return self.person.lookup_key

    @classmethod
    def lookup(cls, key):
        p = Person.lookup(key)
Enrico Zini's avatar
Enrico Zini committed
873
874
        if p is None:
            return None
875
876
        return p.am_or_none

877
878
879
880
881
882
883
    @classmethod
    def lookup_or_404(cls, key):
        from django.http import Http404
        res = cls.lookup(key)
        if res is not None:
            return res
        raise Http404