Commit 0181a3ec authored by Arkadiusz Hiler's avatar Arkadiusz Hiler

Make email addresses for incoming emails case-insensitive

Quoting RFC: "However, exploiting the case sensitivity of mailbox
local-parts impedes interoperability and is discouraged."

Most of the existing software is threating the local part (i.e. the
thing before @) of emails as case insensitive.

Some people use different capitalization at different times, e.g.
arkadiusz.hiler@example.com with git-send-email and
Arkadiusz.Hiler@example.com with their regular client.

To mitigate this Person's email is now case insensitive for the sake of
searching and normalized to lower case pre_save.

It's not perfect by any means and still can be bypassed by doing
.update() on the QuerySet, but will work in most of the usual cases.

Tests and migration deduplicating existing entries are provided.

Fixes: #32Signed-off-by: default avatarArkadiusz Hiler <arkadiusz.hiler@intel.com>
parent f4f47a4e
Pipeline #177195 passed with stage
in 1 minute and 31 seconds
......@@ -25,6 +25,22 @@ import hashlib
from django.db import models
class CaseInsensitiveCharField(models.CharField):
CONVERTIBLES = ('exact', 'exact', 'contains', 'startswith',
'endswith', 'regex')
def get_lookup(self, lookup_name):
if lookup_name in self.CONVERTIBLES:
lookup_name = f"i{lookup_name}"
return super().get_lookup(lookup_name)
def pre_save(self, model_instance, add):
attr = super().pre_save(model_instance, add)
attr = attr.lower()
setattr(model_instance, self.attname, attr)
return attr
class HashField(models.CharField):
def __init__(self, *args, **kwargs):
......
# The MIT License (MIT)
#
# Copyright (c) 2020 Arkadiusz Hiler
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from itertools import groupby
"""Testing migration logic is hard - you cannot call custom methods on model to
avoid breakages by changes in there. Containing all the data migration logic in
the migration file is also not an option - you can't import it and test it
easily.
To mitigate that issue this file is created where the data migration logic can
be contained and both tested and used in the migration file proper.
"""
def deduplicate_persons(person):
persons = person.objects.all()
persons = sorted(persons, key=lambda x: x.email.lower())
persons = groupby(persons, key=lambda x: x.email.lower())
duplicates = []
for email, objs in persons:
objs = list(objs)
if len(objs) > 1:
duplicates.append(objs)
for dupes in duplicates:
main = dupes.pop()
for dupe in dupes:
for comment in dupe.comment_set.all():
comment.submitter = main
comment.save()
for patch in dupe.patch_set.all():
patch.submitter = main
patch.save()
for series in dupe.series_set.all():
series.submitter = main
series.save()
dupe = person.objects.get(pk=dupe.pk)
dupe.delete()
# Generated by Django 2.2.14 on 2020-07-13 23:27
from django.db import migrations
from patchwork.migration_helpers import deduplicate_persons
import patchwork.fields
def migrate_deduplicate_persons(apps, schema_editor):
person = apps.get_model('patchwork', 'Person')
deduplicate_persons(person)
class Migration(migrations.Migration):
dependencies = [
('patchwork', '0036_auto_20200715_0047'),
]
operations = [
migrations.AlterField(
model_name='person',
name='email',
field=patchwork.fields.CaseInsensitiveCharField(max_length=255, unique=True),
),
migrations.RunPython(migrate_deduplicate_persons),
]
......@@ -35,12 +35,12 @@ from django.db.models import Q
import django.dispatch
from django.utils.functional import cached_property
from patchwork.fields import HashField
from patchwork.fields import HashField, CaseInsensitiveCharField
from patchwork.parser import hash_patch, extract_tags
class Person(models.Model):
email = models.CharField(max_length=255, unique=True)
email = CaseInsensitiveCharField(max_length=255, unique=True)
name = models.CharField(max_length=255, null=True, blank=True)
user = models.ForeignKey(User, null=True, blank=True,
on_delete=models.SET_NULL)
......
# The MIT License (MIT)
#
# Copyright (c) 2020 Arkadiusz Hiler
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from patchwork.models import Comment, Patch, Person, Series
from patchwork.tests.utils import defaults
from patchwork.migration_helpers import deduplicate_persons
from django.test import TestCase
class TestDeduplicatePersons(TestCase):
fixtures = ['default_states', 'default_events']
def setUp(self):
defaults.project.save()
self.p1 = Person(email="arkadiusz@example.com", name="Arek")
self.p2 = Person(email="x@example.com", name="Arek")
self.p1.save()
self.p2.save()
# let's create the conflict skipping the regular validaiton
Person.objects.filter(email="x@example.com") \
.update(email='Arkadiusz@example.com')
self.assertEqual(2, Person.objects.count())
def testUnifiesCorrectly(self):
deduplicate_persons(Person)
self.assertEqual(1, Person.objects.count())
def testDoesNotRemoveRelateSeries(self):
Series(project=defaults.project, submitter=self.p1).save()
Series(project=defaults.project, submitter=self.p2).save()
deduplicate_persons(Person)
person = Person.objects.get()
for s in Series.objects.all():
self.assertEqual(s.submitter, person)
def testDoesNotRemoveRelatePatchesAndComments(self):
patch1 = Patch(msgid="1", project=defaults.project, submitter=self.p1)
patch2 = Patch(msgid="2", project=defaults.project, submitter=self.p2)
patch1.save()
patch2.save()
Comment(patch=patch1, submitter=self.p2).save()
Comment(patch=patch2, submitter=self.p1).save()
deduplicate_persons(Person)
person = Person.objects.get()
for p in Patch.objects.all():
self.assertEqual(p.submitter, person)
for c in Comment.objects.all():
self.assertEqual(c.submitter, person)
......@@ -21,6 +21,7 @@ from __future__ import absolute_import
import json
from django.test import TestCase
from django.db.utils import IntegrityError
from patchwork.models import Person
......@@ -63,3 +64,39 @@ class PersonModelTest(TestCase):
def testEmailNameQuoted(self):
p = Person(name="Name, Test", email="test@example.com")
self.assertEqual(p.email_name(), '"Name, Test" <test@example.com>')
def testEmailCaseInsensitiveSearch(self):
p = Person(name='TestName', email='TestName@example.com')
p.save()
self.assertEquals('testname@example.com', p.email)
p1 = Person.objects.get(email='testname@example.com')
p2 = Person.objects.get(email='TestName@example.com')
p3 = Person.objects.get(email__contains='TestName@example.com')
p4 = Person.objects.get(email__contains='testname@example.com')
p5 = Person.objects.get(email__regex='TestName@example.com')
p6 = Person.objects.get(email__regex='testname@example.com')
self.assertEquals(p1, p)
self.assertEquals(p2, p)
self.assertEquals(p3, p)
self.assertEquals(p4, p)
self.assertEquals(p5, p)
self.assertEquals(p6, p)
def testEmailCaseInsnitiveDuplicatesLowercase(self):
p = Person(name='TestName', email='TestName@example.com')
p.save()
p2 = Person(name='Test', email='testname@example.com')
with self.assertRaises(IntegrityError):
p2.save()
def testEmailCaseInsnitiveDuplicatesUppercase(self):
p = Person(name='TestName', email='TestName@example.com')
p.save()
p2 = Person(name='Test', email='TestName@example.com')
with self.assertRaises(IntegrityError):
p2.save()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment