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)
Exemple #3
0
 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)
Exemple #5
0
 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)
Exemple #6
0
 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)
Exemple #7
0
 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)
Exemple #9
0
    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)
Exemple #10
0
 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)
Exemple #11
0
    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)
Exemple #12
0
    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)
Exemple #13
0
    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)
Exemple #14
0
 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,
     )
Exemple #15
0
    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
Exemple #16
0
    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)
Exemple #17
0
    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)
Exemple #18
0
    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())
Exemple #20
0
 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)
Exemple #21
0
    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)
Exemple #22
0
    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)
Exemple #23
0
 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)
Exemple #24
0
    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)
Exemple #26
0
    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)
Exemple #27
0
    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)
Exemple #28
0
    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)
Exemple #30
0
    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)
Exemple #32
0
 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)
Exemple #35
0
 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)
Exemple #36
0
 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)
Exemple #40
0
 def retrieve(self, request, *args, **kwargs):
     self.serializer_class = PaperDetailSerializer
     return ModelViewSet.retrieve(self, request, args, kwargs)
Exemple #41
0
 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)
Exemple #43
0
 def retrieve(self, request, *args, **kwargs):
     return ModelViewSet.retrieve(self, request, *args, **kwargs)
Exemple #44
0
 def perform_create(self, serializer):
     serializer.validated_data['current_user'] = self.request.user
     return ModelViewSet.perform_create(self, serializer)
Exemple #45
0
 def update(self, request, *args, **kwargs):
     return ModelViewSet.update(self,
                                request,
                                *args,
                                partial=True,
                                **kwargs)
Exemple #46
0
 def list(self, request, *args, **kwargs):
     return ModelViewSet.list(self, request, *args, **kwargs)
Exemple #47
0
 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)
Exemple #48
0
 def destroy(self, request, *args, **kwargs):
     return ModelViewSet.destroy(self, request, *args, **kwargs)
Exemple #49
0
 def perform_create(self, serializer):
     application_type = self.get_application_type()
     serializer.validated_data['application_type'] = application_type
     return ModelViewSet.perform_create(self, serializer)
Exemple #50
0
 def create(self, request, *args, **kwargs):
     request.data['application'] = kwargs['application']
     return ModelViewSet.create(self, request, *args, **kwargs)
Exemple #51
0
 def list(self, request, *args, **kwargs):
     return ModelViewSet.list(self, request, *args, **kwargs)
 def create(self, request, *args, **kwargs):
     return ModelViewSet.create(self, request, *args, **kwargs)
Exemple #53
0
 def retrieve(self, request, *args, **kwargs):
     return ModelViewSet.retrieve(self, request, *args, **kwargs)
Exemple #54
0
 def serialize_all(view_set: viewsets.ModelViewSet) -> list:
     return view_set.as_view({'get': 'list'})(request._request).data
Exemple #55
0
 def destroy(self, request, *args, **kwargs):
     return ModelViewSet.destroy(self, request, *args, **kwargs)