11from allauth .account .models import EmailAddress
22from django .contrib .auth import get_user_model
3- from django .core .exceptions import ValidationError
43from django .utils .translation import gettext_lazy as _
54from drf_yasg .utils import swagger_auto_schema
65from rest_framework import pagination
76from rest_framework .authtoken .views import ObtainAuthToken
8- from rest_framework .exceptions import NotFound
97from rest_framework .generics import (
108 GenericAPIView ,
119 ListCreateAPIView ,
2018
2119from openwisp_users .api .permissions import DjangoModelPermissions
2220
21+ from .mixins import FilterByParent
2322from .mixins import ProtectedAPIMixin as BaseProtectedAPIMixin
2423from .serializers import (
2524 ChangePasswordSerializer ,
@@ -198,7 +197,7 @@ def update(self, request, *args, **kwargs):
198197 )
199198
200199
201- class BaseEmailView (ProtectedAPIMixin , GenericAPIView ):
200+ class BaseEmailView (ProtectedAPIMixin , FilterByParent , GenericAPIView ):
202201 model = EmailAddress
203202 serializer_class = EmailAddressSerializer
204203
@@ -209,28 +208,22 @@ def initial(self, *args, **kwargs):
209208 super ().initial (* args , ** kwargs )
210209 self .assert_parent_exists ()
211210
212- def assert_parent_exists (self ):
213- try :
214- assert self .get_parent_queryset ().exists ()
215- except (AssertionError , ValidationError ):
216- user_id = self .kwargs ['pk' ]
217- raise NotFound (detail = _ ("User with ID '{}' not found." .format (user_id )))
218-
219211 def get_parent_queryset (self ):
220- user = self .request .user
221-
222- if user .is_superuser :
223- return User .objects .filter (pk = self .kwargs ['pk' ])
224-
225- org_users = OrganizationUser .objects .filter (user = user ).select_related (
226- 'organization'
227- )
228- qs_user = User .objects .none ()
229- for org_user in org_users :
230- if org_user .is_admin :
231- qs_user = qs_user | org_user .organization .users .all ().distinct ()
232- qs_user = qs_user .filter (is_superuser = False )
233- return qs_user .filter (pk = self .kwargs ['pk' ])
212+ qs = User .objects .filter (pk = self .kwargs ['pk' ])
213+ if self .request .user .is_superuser :
214+ return qs
215+ return self .get_organization_queryset (qs )
216+
217+ def get_organization_queryset (self , qs ):
218+ orgs = self .request .user .organizations_managed
219+ app_label = User ._meta .app_config .label
220+ filter_kwargs = {
221+ # exclude superusers
222+ 'is_superuser' : False ,
223+ # ensure user is member of the org
224+ f'{ app_label } _organizationuser__organization_id__in' : orgs ,
225+ }
226+ return qs .filter (** filter_kwargs ).distinct ()
234227
235228 def get_serializer_context (self ):
236229 if getattr (self , 'swagger_fake_view' , False ):
0 commit comments