def test_authenticated_whitelisted(self): """ An authenticated, un-whitelisted IP address should be granted permission""" factory = APIRequestFactory() request = factory.get("api/users") request.user = self.user permission = permissions.IsAuthenticatedOrWhitelist() view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_permission(request, view), True)
def test_has_object_permission_user_on_admin(self): """ Makes sure a regular user cannot access other users""" factory = APIRequestFactory() request = factory.get("api/users") request.user = self.user permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_object_permission(request, view, self.admin), False)
def test_authenticated_whitelisted(self): """ An authenticated, un-whitelisted IP address should be granted permission""" factory = APIRequestFactory() request = factory.get('api/users') request.user = self.user permission = permissions.IsAuthenticatedOrWhitelist() view = ModelViewSet() view.action = 'retrieve' self.assertEqual(permission.has_permission(request, view), True)
def test_has_object_permission_admin_on_user(self): """ Makes sure an admin user has permissions to access another user""" factory = APIRequestFactory() request = factory.get("api/users") request.user = self.admin permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_object_permission(request, view, self.user), True)
def test_unauthenticated_not_whitelisted(self): """ An unauthenticated, un-whitelisted IP address should not be granted permission""" factory = APIRequestFactory() request = factory.get('api/users') request.META['REMOTE_ADDR'] = '255.255.255.0' request.user = False permission = permissions.IsAuthenticatedOrWhitelist() view = ModelViewSet() view.action = 'retrieve' self.assertEqual(permission.has_permission(request, view), False)
def test_has_object_permission_admin_on_admin(self): """ Makes sure an admin user has permissions to access themselves""" factory = APIRequestFactory() request = factory.get('api/users') request.user = self.admin permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = 'retrieve' self.assertEqual( permission.has_object_permission(request, view, self.admin), True)
def test_has_object_permission_user_on_admin(self): """ Makes sure a regular user cannot access other users""" factory = APIRequestFactory() request = factory.get('api/users') request.user = self.user permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = 'retrieve' self.assertEqual( permission.has_object_permission(request, view, self.admin), False)
def test_unauthenticated_not_whitelisted(self): """ An unauthenticated, un-whitelisted IP address should not be granted permission""" factory = APIRequestFactory() request = factory.get("api/users") request.META["REMOTE_ADDR"] = "255.255.255.0" request.user = False permission = permissions.IsAuthenticatedOrWhitelist() view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_permission(request, view), False)
def create(self, request, *args, **kwargs): """ Create new reseller client """ application = Application.objects.filter(owner=request.user).first() if application: reseller = get_object_or_403(Reseller, name=kwargs['reseller_name'], application=application) else: reseller = get_object_or_403(Reseller, name=kwargs['reseller_name'], owner=request.user) if not Client.objects.filter(reseller=reseller, name=request.data['name']): # Check if there is a free space for new client or storage is unlimited space = free_space(reseller) if space >= request.data['storage'][ 'limit'] or reseller.limit is UNLIMITED: # Every client should belong to particular reseller request.data['reseller'] = reseller return ModelViewSet.create(self, request, *args, **kwargs) return Response("Reseller limit is reached", status=status.HTTP_400_BAD_REQUEST) return Response("Such client already exists", status=status.HTTP_400_BAD_REQUEST)
def list(self, request, *args, **kwargs): """ Method is overwritten in order to implement superuser check """ if request.user.is_superuser: return ModelViewSet.list(self, request, *args, **kwargs) return Response("Only superuser can get resellers list", status=status.HTTP_403_FORBIDDEN)
def retrieve(self, request, *args, **kwargs): if request.user.is_superuser: get_object_or_403(Reseller, pk=kwargs['reseller_pk']) else: get_object_or_403(Reseller, pk=kwargs['reseller_pk'], owner=request.user) return ModelViewSet.retrieve(self, request, *args, **kwargs)
def create(self, *args, **kwargs): request = args[0] client = kwargs['client'] reseller = kwargs['reseller'] if 'user_id' in request.data and ClientUser.objects.filter(user_id=request.data['user_id'], client=kwargs['client']): return Response("Such user already exists", status=status.HTTP_400_BAD_REQUEST) if 'email' in request.data and ClientUser.objects.filter(email=request.data['email'], client=kwargs['client']): return Response("User with email {} already exists".format(request.data['email']), status=status.HTTP_400_BAD_REQUEST) if 'usage' in request.data: return Response("Usage should not be specified", status=status.HTTP_400_BAD_REQUEST) # Check if client has free space for new user or storage is unlimited space = free_space(client) if space >= request.data['storage']['limit'] or space is UNLIMITED: request.data['client'] = client request.data['application_id'] = reseller.application.id if 'admin' not in request.data: request.data['admin'] = False if 'superadmin' not in request.data: request.data['superadmin'] = False if 'password' in request.data: request.data.pop('password') if 'profile_type' in request.data: if not request.data['profile_type']: request.data['profile_type'] = ClientUser.DEFAULT_PROFILE return ModelViewSet.create(self, *args, **kwargs) return Response("Client limit is reached", status=status.HTTP_400_BAD_REQUEST)
def update(self, request, *args, **kwargs): instence = ModelViewSet.get_object(self) sku_ID = request.data.get('sku') image = request.data.get('image') if not all([sku_ID]): return Response({'detail':'数据不完整'},status=400) if image: image_client = Fdfs_client(settings.FASTDFS_PATH) image_client.delete_file(instence.image.name) data = image_client.upload_by_buffer(image.read()) instence.image = data.get('Remote file_id') instence.sku_id = sku_ID instence.save() serializer = self.get_serializer(instence) return Response(serializer.data,status=200)
def get_queryset(self): base_queryset = ModelViewSet.get_queryset(self) request = self.request user = request.user return OwnerPolicyPermissionHelper.filter_queryset( user=user, queryset=base_queryset, )
def retrieve(self, request, *args, **kwargs): account = request.account post = self.get_object() if not account or account.pk != post.account.pk: post.views_count += 1 post.save() result = ModelViewSet.retrieve(self, request, *args, **kwargs) return result
def retrieve(self, request, *args, **kwargs): """ Return particular client which owned by particular reseller """ if request.user.is_superuser: get_object_or_403(Reseller, pk=kwargs['reseller_pk']) else: get_object_or_403(Reseller, pk=kwargs['reseller_pk'], owner=request.user) return ModelViewSet.retrieve(self, request, *args, **kwargs)
def list(self, request, *args, **kwargs): patient = request.query_params.get('patient') if patient != None: patient = Patient.objects.get(id=patient) queryset = self.get_queryset().filter(patient=patient) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) return ModelViewSet.list(self, request, *args, **kwargs)
def create(self, request, *args, **kwargs): if isinstance(request.data, QueryDict): _mutable = request.data._mutable request.data._mutable = True request.data['doctor'] = Doctor.objects.get(user=request.user).id if isinstance(request.data, QueryDict): request.data._mutable = _mutable return ModelViewSet.create(self, request, *args, **kwargs)
def handle(self, *args, **options): prepare(options["force"], options["sudo"]) from rest_framework.viewsets import ModelViewSet for viewset in ModelViewSet.__subclasses__(): name = viewset().get_serializer_class( ).Meta.model._meta.model_name.title() for GeneratorClass in [FormGenerator, ListGenerator]: generator = GeneratorClass(viewset) with overwrite(generator.filename) as f: f.write(generator.render())
def create(self, request, *args, **kwargs): request.data['usuario_solicitante'] = request.user.id request.data['fecha_emision'] = self._normalizar_fecha( request.data['fecha_emision']) dpc = request.data.get('destino_domicilio_provincia') opc = request.data.get('origen_domicilio_provincia') request.data['destino_domicilio_provincia'] = Provincia.objects.get( codigo=dpc).codigo_arba request.data['origen_domicilio_provincia'] = Provincia.objects.get( codigo=opc).codigo_arba request.data['fecha_salida_transporte'] = self._normalizar_fecha( request.data['fecha_salida_transporte']) return ModelViewSet.create(self, request, *args, **kwargs)
def create(self, request, *args, **kwargs): """ Create new reseller client """ if request.user.is_superuser: reseller = get_object_or_403(Reseller, pk=kwargs['reseller_pk']) else: reseller = get_object_or_403(Reseller, pk=kwargs['reseller_pk'], owner=request.user) # Check if there is a free space for new client free_space = reseller.limit - reseller.get_usage() if free_space >= request.data['storage']['limit']: # Every client should belong to particular reseller request.data['reseller'] = reseller return ModelViewSet.create(self, request, *args, **kwargs) return Response("Reseller limit is reached", status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): if request.user.is_superuser: reseller = get_object_or_403(Reseller, pk=kwargs['reseller_pk']) else: reseller = get_object_or_403(Reseller, pk=kwargs['reseller_pk'], owner=request.user) # get client to provide it for user creation client = Client.objects.filter(reseller=reseller, pk=kwargs['client_pk']).first() if client: # Check if client has free space for new user free_space = client.limit - client.get_usage() if free_space >= request.data['storage']['limit']: request.data['client'] = client.id return ModelViewSet.create(self, request, *args, **kwargs) return Response('Client limit is reached', status=status.HTTP_400_BAD_REQUEST) return Response('Current reseller does not have permissions for this client', status=status.HTTP_403_FORBIDDEN)
def handle(self, *args, **options): # print(''.join(apis())) path = os.getcwd() prepare() os.chdir(path) from rest_framework.viewsets import ModelViewSet for viewset in ModelViewSet.__subclasses__(): if viewset.__module__ != 'django_react_admin.views': name = viewset().get_serializer_class( ).Meta.model._meta.model_name.title() code = vuetify(generate_vue_form(viewset)) path = f'frontend/src/components/{name}.vue' if os.path.exists( path) and input(f'Overwrite {path}? y/n ') != 'y': continue open(path, 'w').write(code) with open(path, 'w') as f: f.write(code)
def test_has_permission_no_auth(self): """View level returns true if the request is a retrieve, otherwise false""" factory = APIRequestFactory() request = factory.get('api/users') permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = 'retrieve' self.assertEqual(permission.has_permission(request, view), True) view.action = 'list' self.assertEqual(permission.has_permission(request, view), False) view.action = 'create' self.assertEqual(permission.has_permission(request, view), False) view.action = 'update' self.assertEqual(permission.has_permission(request, view), False) view.action = 'partial_update' self.assertEqual(permission.has_permission(request, view), False) view.action = 'destroy' self.assertEqual(permission.has_permission(request, view), False)
def _update_self(self, request, user_id=None): """ Updates itself """ user = User.objects.get(pk=user_id) data = request.data partial = False if 'profile' in data: if user.profile != data['profile']: raise PermissionDenied else: partial = True if 'is_active' in data: if data['is_active'] == str(False): raise PermissionDenied else: partial = True return ModelViewSet.update(self, request, user_id, partial=partial)
def create(self, request, *args, **kwargs): """ Create new reseller client """ application = Application.objects.filter(owner=request.user).first() if application: reseller = get_object_or_403(Reseller, name=kwargs['reseller_name'], application=application) else: reseller = get_object_or_403(Reseller, name=kwargs['reseller_name'], owner=request.user) if not Client.objects.filter(reseller=reseller, name=request.data['name']): # Check if there is a free space for new client or storage is unlimited space = free_space(reseller) if space >= request.data['storage']['limit'] or reseller.limit is UNLIMITED: # Every client should belong to particular reseller request.data['reseller'] = reseller return ModelViewSet.create(self, request, *args, **kwargs) return Response("Reseller limit is reached", status=status.HTTP_400_BAD_REQUEST) return Response("Such client already exists", status=status.HTTP_400_BAD_REQUEST)
def create(self, *args, **kwargs): request = args[0] client = kwargs['client'] reseller = kwargs['reseller'] if 'user_id' in request.data and ClientUser.objects.filter( user_id=request.data['user_id'], client=kwargs['client']): return Response("Such user already exists", status=status.HTTP_400_BAD_REQUEST) if 'email' in request.data and ClientUser.objects.filter( email=request.data['email'], client=kwargs['client']): return Response("User with email {} already exists".format( request.data['email']), status=status.HTTP_400_BAD_REQUEST) if 'usage' in request.data: return Response("Usage should not be specified", status=status.HTTP_400_BAD_REQUEST) # Check if client has free space for new user or storage is unlimited space = free_space(client) if space >= request.data['storage']['limit'] or space is UNLIMITED: request.data['client'] = client request.data['application_id'] = reseller.application.id if 'admin' not in request.data: request.data['admin'] = False if 'superadmin' not in request.data: request.data['superadmin'] = False if 'password' in request.data: request.data.pop('password') if 'profile_type' in request.data: if not request.data['profile_type']: request.data['profile_type'] = ClientUser.DEFAULT_PROFILE return ModelViewSet.create(self, *args, **kwargs) return Response("Client limit is reached", status=status.HTTP_400_BAD_REQUEST)
def test_has_permission_admin_user(self): """View level returns true if the user is staff """ factory = APIRequestFactory() request = factory.get('api/users') request.user = self.admin permission = permissions.IsStaffOrTargetUser() force_authenticate(request, self.admin) view = ModelViewSet() view.action = 'retrieve' self.assertEqual(permission.has_permission(request, view), True) view.action = 'list' self.assertEqual(permission.has_permission(request, view), True) view.action = 'create' self.assertEqual(permission.has_permission(request, view), True) view.action = 'update' self.assertEqual(permission.has_permission(request, view), True) view.action = 'partial_update' self.assertEqual(permission.has_permission(request, view), True) view.action = 'destroy' self.assertEqual(permission.has_permission(request, view), True)
def test_has_permission_no_auth(self): """View level returns true if the request is a retrieve, otherwise false""" factory = APIRequestFactory() request = factory.get("api/users") permission = permissions.IsStaffOrTargetUser() view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_permission(request, view), True) view.action = "list" self.assertEqual(permission.has_permission(request, view), False) view.action = "create" self.assertEqual(permission.has_permission(request, view), False) view.action = "update" self.assertEqual(permission.has_permission(request, view), False) view.action = "partial_update" self.assertEqual(permission.has_permission(request, view), False) view.action = "destroy" self.assertEqual(permission.has_permission(request, view), False)
def list(self, request, *args, **kwargs): anamnesis = request.query_params.get('anamnesis') cell_extraction = request.query_params.get('cell_extraction') if anamnesis == None and cell_extraction != None: cell_extraction = CellExtraction.objects.get(id=cell_extraction) queryset = self.get_queryset().filter( cell_extraction=cell_extraction) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) elif cell_extraction == None and anamnesis != None: anamnesis = Anamnesis.objects.get(id=anamnesis) queryset = self.get_queryset().filter( anamnesis=anamnesis, cell_extraction=cell_extraction) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) elif cell_extraction != None and anamnesis != None: anamnesis = Anamnesis.objects.get(id=anamnesis) cell_extraction = CellExtraction.objects.get(id=cell_extraction) queryset = self.get_queryset().filter( anamnesis=anamnesis, cell_extraction=cell_extraction) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) return ModelViewSet.list(self, request, *args, **kwargs)
def test_has_permission_admin_user(self): """View level returns true if the user is staff """ factory = APIRequestFactory() request = factory.get("api/users") request.user = self.admin permission = permissions.IsStaffOrTargetUser() force_authenticate(request, self.admin) view = ModelViewSet() view.action = "retrieve" self.assertEqual(permission.has_permission(request, view), True) view.action = "list" self.assertEqual(permission.has_permission(request, view), True) view.action = "create" self.assertEqual(permission.has_permission(request, view), True) view.action = "update" self.assertEqual(permission.has_permission(request, view), True) view.action = "partial_update" self.assertEqual(permission.has_permission(request, view), True) view.action = "destroy" self.assertEqual(permission.has_permission(request, view), True)
def create(self, request, *args, **kwargs): request.data['application'] = kwargs['application'] return ModelViewSet.create(self, request, *args, **kwargs)
def list(self, request, *args, **kwargs): queryset = Resume.objects.filter(author=request.user) return ModelViewSet.list(self, request, *args, **kwargs)
def create(self, request, *args, **kwargs): return ModelViewSet.create(self, request, *args, **kwargs)
def create(self, request, *args, **kwargs): if request.user.is_superuser: return ModelViewSet.create(self, request, *args, **kwargs) return Response("Only superuser can create reseller", status=status.HTTP_403_FORBIDDEN)
def get_queryset(self): application_type = self.get_application_type() queryset = ModelViewSet.get_queryset(self) return queryset.filter( application_type__pk=application_type.pk )
def destroy(self, request, pk=None): return ModelViewSet.destroy(self, request, pk=pk)
def update(self, request, pk=None): product = self.get_object() data = request.data return ModelViewSet.update(self, request, pk)
def retrieve(self, request, pk=None): return ModelViewSet.retrieve(self, request, pk)
def retrieve(self, request, *args, **kwargs): self.serializer_class = PaperDetailSerializer return ModelViewSet.retrieve(self, request, args, kwargs)
def create(self, request, *args, **kwargs): username = str(int(math.ceil(random.random() * 1000000))) while len(User.objects.filter(username=username)) > 0: username = str(int(math.ceil(random.random() * 1000000))) request.data['username'] = username return ModelViewSet.create(self, request, args, kwargs)
def update(self, request, *args, **kwargs): return ModelViewSet.update(self, request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs): return ModelViewSet.retrieve(self, request, *args, **kwargs)
def perform_create(self, serializer): serializer.validated_data['current_user'] = self.request.user return ModelViewSet.perform_create(self, serializer)
def update(self, request, *args, **kwargs): return ModelViewSet.update(self, request, *args, partial=True, **kwargs)
def list(self, request, *args, **kwargs): return ModelViewSet.list(self, request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs): if request.user.is_superuser: return ModelViewSet.retrieve(self, request, *args, **kwargs) return Response("Only superuser can get reseller information", status=status.HTTP_403_FORBIDDEN)
def destroy(self, request, *args, **kwargs): return ModelViewSet.destroy(self, request, *args, **kwargs)
def perform_create(self, serializer): application_type = self.get_application_type() serializer.validated_data['application_type'] = application_type return ModelViewSet.perform_create(self, serializer)
def serialize_all(view_set: viewsets.ModelViewSet) -> list: return view_set.as_view({'get': 'list'})(request._request).data