Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TTVA-199 | Allow duplicate email addresses #181

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions respa/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ def get_git_revision_hash():

SOCIALACCOUNT_PROVIDERS = {"tampere": {"VERIFIED_EMAIL": True}}
LOGIN_REDIRECT_URL = "/"
ACCOUNT_UNIQUE_EMAIL = False
ACCOUNT_LOGOUT_ON_GET = True
SOCIALACCOUNT_ADAPTER = "tamusers.adapter.SocialAccountAdapter"

Expand Down
3 changes: 2 additions & 1 deletion users/api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from allauth.socialaccount.models import EmailAddress
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework import permissions, serializers, generics, viewsets, status
from rest_framework.decorators import action
Expand Down Expand Up @@ -97,7 +98,7 @@ def set_email(self, request, pk=None):
status=status.HTTP_400_BAD_REQUEST
)

if EmailAddress.objects.filter(email=email):
if settings.ACCOUNT_UNIQUE_EMAIL and EmailAddress.objects.filter(email=email):
return Response(
{"detail": "The email address is already in use."},
status=status.HTTP_400_BAD_REQUEST
Expand Down
37 changes: 37 additions & 0 deletions users/migrations/0012_allow_duplicate_account_emailaddresses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from django.db import migrations

class Migration(migrations.Migration):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should check if the constraint exists before trying to remove it. Would something like this work:

from django.db import migrations, models
from django.db.utils import OperationalError

def check_constraint_exists(apps, schema_editor):
    # Get the connection to the database
    connection = schema_editor.connection

    constraint_name = 'account_emailaddress_email_key'
    table_name = 'account_emailaddress'

    # Check if the constraint exists
    sql = f"""
    SELECT conname
    FROM pg_constraint
    WHERE conname = '{constraint_name}' AND conrelid = '{table_name}'::regclass;
    """

    with connection.cursor() as cursor:
        cursor.execute(sql)
        result = cursor.fetchone()
        return result is not None

def modify_constraints(apps, schema_editor):
    if check_constraint_exists(apps, schema_editor):
        # Remove the existing unique constraint on 'email'
        schema_editor.remove_constraint(
            model_name='emailaddress',
            name='account_emailaddress_email_key',
        )
    
    # Add the new unique constraint on ('user', 'email')
    schema_editor.add_constraint(
        model_name='emailaddress',
        constraint=models.UniqueConstraint(
            fields=['user', 'email'],
            name='account_emailaddress_email_key',
        ),
    )

class Migration(migrations.Migration):

    dependencies = [
        ('account', '0002_email_max_length'),
        ('users', '0011_change_last_name_length'),
    ]

    operations = [
        migrations.RunPython(modify_constraints),
    ]

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking something like this:

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('account', '0002_email_max_length'),
        ('users', '0011_change_last_name_length'),
    ]

    operations = [
        migrations.RunSQL(
            sql=[
                """
                DO $$ 
                DECLARE
                    r RECORD;
                BEGIN
                    FOR r IN 
                        SELECT conname 
                        FROM pg_constraint
                        JOIN pg_class ON conrelid = pg_class.oid
                        WHERE pg_class.relname = 'account_emailaddress'
                            AND conname LIKE '%email%'
                            AND contype = 'u'
                    LOOP
                        EXECUTE 'ALTER TABLE account_emailaddress DROP CONSTRAINT ' || r.conname;
                    END LOOP;
                END $$;
                """,
                "ALTER TABLE account_emailaddress ADD CONSTRAINT account_emailaddress_email_key UNIQUE (user_id, email);",
            ],
            reverse_sql=[
                "ALTER TABLE account_emailaddress DROP CONSTRAINT account_emailaddress_email_key;",
                "ALTER TABLE account_emailaddress ADD CONSTRAINT account_emailaddress_email_key UNIQUE (email);",
            ],
        ),
    ]


dependencies = [
('account', '0002_email_max_length'),
('users', '0011_change_last_name_length'),
]

operations = [
migrations.RunSQL(
sql=[
"""
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN
SELECT conname
FROM pg_constraint
JOIN pg_class ON conrelid = pg_class.oid
WHERE pg_class.relname = 'account_emailaddress'
AND conname LIKE '%email%'
AND contype = 'u'
LOOP
EXECUTE 'ALTER TABLE account_emailaddress DROP CONSTRAINT ' || r.conname;
END LOOP;
END $$;
""",
"ALTER TABLE account_emailaddress ADD CONSTRAINT account_emailaddress_email_key UNIQUE (user_id, email);",
],
reverse_sql=[
"ALTER TABLE account_emailaddress DROP CONSTRAINT account_emailaddress_email_key;",
"ALTER TABLE account_emailaddress ADD CONSTRAINT account_emailaddress_email_key UNIQUE (email);",
],
),
]
15 changes: 15 additions & 0 deletions users/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from allauth.account.models import EmailAddress
from django.conf import settings
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
Expand Down Expand Up @@ -64,6 +65,7 @@ def test_set_email_not_provided(self):
self.assertEqual(self.user.email, "")

def test_set_email_already_in_use(self):
settings.ACCOUNT_UNIQUE_EMAIL = True
url = reverse("user-set-email", kwargs={"pk": self.user.pk})
data = {"email": "[email protected]"} # Email already used by other_user

Expand All @@ -74,3 +76,16 @@ def test_set_email_already_in_use(self):
response.data, {"detail": "The email address is already in use."}
)
self.assertEqual(self.user.email, "")

def test_allow_to_set_duplicate_email(self):
settings.ACCOUNT_UNIQUE_EMAIL = False
url = reverse("user-set-email", kwargs={"pk": self.user.pk})
data = {"email": "[email protected]"} # Email already used by other_user

response = self.client.post(url, data, format="json")

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data, {"detail": "Email set successfully."}
)
self.assertEqual(self.user.email, "[email protected]")
Loading