Use database constraint to prevent relationships with yourself.

This commit is contained in:
Adam Kelly 2020-03-14 22:20:01 +00:00
parent 1cdd7ea1fc
commit ffe81291ad
3 changed files with 33 additions and 2 deletions

View file

@ -128,14 +128,15 @@ def handle_incoming_follow(activity):
to_follow = models.User.objects.get(actor=activity['object']) to_follow = models.User.objects.get(actor=activity['object'])
# figure out who they are # figure out who they are
user = get_or_create_remote_user(activity['actor']) user = get_or_create_remote_user(activity['actor'])
# TODO: allow users to manually approve requests
try: try:
request = models.UserFollowRequest.objects.create( request = models.UserFollowRequest.objects.create(
user_subject=user, user_subject=user,
user_object=to_follow, user_object=to_follow,
relationship_id=activity['id'] relationship_id=activity['id']
) )
except django.db.utils.IntegrityError: except django.db.utils.IntegrityError as err:
if err.__cause__.diag.constraint_name != 'userfollowrequest_unique':
raise
# Duplicate follow request. Not sure what the correct behaviour is, but # Duplicate follow request. Not sure what the correct behaviour is, but
# just dropping it works for now. We should perhaps generate the # just dropping it works for now. We should perhaps generate the
# Accept, but then do we need to match the activity id? # Accept, but then do we need to match the activity id?

View file

@ -0,0 +1,26 @@
# Generated by Django 3.0.3 on 2020-03-14 21:52
from django.db import migrations, models
import django.db.models.expressions
class Migration(migrations.Migration):
dependencies = [
('fedireads', '0016_auto_20200313_1337'),
]
operations = [
migrations.AddConstraint(
model_name='userblocks',
constraint=models.CheckConstraint(check=models.Q(_negated=True, user_subject=django.db.models.expressions.F('user_object')), name='userblocks_no_self'),
),
migrations.AddConstraint(
model_name='userfollowrequest',
constraint=models.CheckConstraint(check=models.Q(_negated=True, user_subject=django.db.models.expressions.F('user_object')), name='userfollowrequest_no_self'),
),
migrations.AddConstraint(
model_name='userfollows',
constraint=models.CheckConstraint(check=models.Q(_negated=True, user_subject=django.db.models.expressions.F('user_object')), name='userfollows_no_self'),
),
]

View file

@ -95,6 +95,10 @@ class UserRelationship(FedireadsModel):
models.UniqueConstraint( models.UniqueConstraint(
fields=['user_subject', 'user_object'], fields=['user_subject', 'user_object'],
name='%(class)s_unique' name='%(class)s_unique'
),
models.CheckConstraint(
check=~models.Q(user_subject=models.F('user_object')),
name='%(class)s_no_self'
) )
] ]