Skip to content

Commit

Permalink
Refactored base-email-view
Browse files Browse the repository at this point in the history
  • Loading branch information
MihirKohli committed Sep 28, 2023
1 parent 8403e5a commit 5eb5aad
Showing 1 changed file with 5 additions and 32 deletions.
37 changes: 5 additions & 32 deletions openwisp_users/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
from rest_framework.settings import api_settings
from swapper import load_model

from .mixins import FilterByParent # Import the FilterByParent mixin

from openwisp_users.api.permissions import DjangoModelPermissions

from .mixins import ProtectedAPIMixin as BaseProtectedAPIMixin
Expand Down Expand Up @@ -174,8 +176,8 @@ def get_object(self):
user = User.objects.filter(id=self.request.user.id)
qs = self.get_queryset()
if (
user.first().is_staff is True
and not qs.filter(pk=self.request.user.id).exists()
user.first().is_staff is True
and not qs.filter(pk=self.request.user.id).exists()
):
qs = qs | user
filter_kwargs = {
Expand All @@ -198,44 +200,15 @@ def update(self, request, *args, **kwargs):
)


class BaseEmailView(ProtectedAPIMixin, GenericAPIView):
class BaseEmailView(ProtectedAPIMixin, FilterByParent, GenericAPIView):
model = EmailAddress
serializer_class = EmailAddressSerializer

def get_queryset(self):
return EmailAddress.objects.select_related('user').order_by('id')

def initial(self, *args, **kwargs):
super().initial(*args, **kwargs)
self.assert_parent_exists()

def assert_parent_exists(self):
try:
assert self.get_parent_queryset().exists()
except (AssertionError, ValidationError):
user_id = self.kwargs['pk']
raise NotFound(detail=_("User with ID '{}' not found.".format(user_id)))

def get_parent_queryset(self):
user = self.request.user

if user.is_superuser:
return User.objects.filter(pk=self.kwargs['pk'])

org_users = OrganizationUser.objects.filter(user=user).select_related(
'organization'
)
qs_user = User.objects.none()
for org_user in org_users:
if org_user.is_admin:
qs_user = qs_user | org_user.organization.users.all().distinct()
qs_user = qs_user.filter(is_superuser=False)
return qs_user.filter(pk=self.kwargs['pk'])

def get_serializer_context(self):
if getattr(self, 'swagger_fake_view', False):
# To get rid of assertion error raised in
# the dev server, and for schema generation
return None
context = super().get_serializer_context()
context['user'] = self.get_parent_queryset().first()
Expand Down

0 comments on commit 5eb5aad

Please sign in to comment.