refactor removing user from group

This is in preparation for removing a user and their lists when the group owner blocks them.
Remove the user via models.group
Remove the lists via models.list
This commit is contained in:
Hugh Rundle 2021-10-09 22:11:46 +11:00
parent 1bf5758e01
commit 9940abfd81
3 changed files with 34 additions and 8 deletions

View file

@ -85,6 +85,15 @@ class GroupMember(models.Model):
group=join_request.group,
)
@classmethod
def remove(cls, owner, user):
"""remove a user from a group"""
memberships = cls.objects.filter(group__user=owner, user=user).all()
for m in memberships:
# remove this user
m.delete()
class GroupMemberInvitation(models.Model):
"""adding a user to a group requires manual confirmation"""

View file

@ -2,6 +2,7 @@
from django.apps import apps
from django.db import models
from django.db.models import Q
from django.db.models.fields import NullBooleanField
from django.utils import timezone
from bookwyrm import activitypub
@ -87,7 +88,24 @@ class List(OrderedCollectionMixin, BookWyrmModel):
def direct_filter(cls, queryset, viewer):
"""Override filter for "direct" privacy level to allow group members to see the existence of group lists"""
return queryset.exclude(~Q(group__memberships__user=viewer), privacy="direct")
return queryset.exclude(
~Q( # user not self and not in the group if this is a group list
Q(user=viewer) | Q(group__memberships__user=viewer)
),
privacy="direct"
)
@classmethod
def remove_from_group(cls, owner, user):
"""remove a list from a group"""
memberships = GroupMember.objects.filter(group__user=owner, user=user).all()
for m in memberships:
# remove this user's group-curated lists from the group
cls.objects.filter(group=m.group, user=m.user).update(
group=None, curation="closed"
)
class ListItem(CollectionItemMixin, BookWyrmModel):
"""ok"""

View file

@ -163,6 +163,10 @@ def remove_member(request):
if not user:
return HttpResponseBadRequest()
# you can't be removed from your own group
if request.POST["user"]== group.user:
return HttpResponseBadRequest()
is_member = models.GroupMember.objects.filter(group=group, user=user).exists()
is_invited = models.GroupMemberInvitation.objects.filter(
group=group, user=user
@ -182,13 +186,8 @@ def remove_member(request):
if is_member:
try:
membership = models.GroupMember.objects.get(group=group, user=user)
membership.delete()
# remove this user's group-curated lists from the group
models.List.objects.filter(group=group, user=user).update(
group=None, curation="closed"
)
models.List.remove_from_group(group.user, user)
models.GroupMember.remove(group.user, user)
except IntegrityError:
pass