def _staff_or_instructor_delete_list(self, request, **kwargs): # ETAPA 1 - Desserialização e validação dos dados recebidos # --------------------------------------------------------- course_id = course_id_decoder(kwargs['pk']) staff_or_instructor = kwargs['staff_or_instructor'] deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = Bundle(data=dict_strip_unicode_keys(deserialized), request=request) if 'user_resource_uri' in bundle.data: user_resource_uri = bundle.data['user_resource_uri'] bundle.data['course_id'] = course_id bundle.data['staff_or_instructor'] = kwargs['staff_or_instructor'] validation = CleanedDataFormValidation(form_class=CourseDeleteUserForm) validation_errors = validation.is_valid(bundle) if validation_errors: raise ImmediateHttpResponse(response=self.error_response( bundle.request, validation_errors)) # ETAPA 2 - Efetuando operações no EDX # ------------------------------------ username = user_resource_uri.split('/')[-2:-1][0] course_remove_user(course_id, username, staff_or_instructor) return http.HttpNoContent()
def post_list(self, request, **kwargs): # ETAPA 1 - Desserialização e validação dos dados recebidos # --------------------------------------------------------- deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = Bundle(data=dict_strip_unicode_keys(deserialized), request=request) validation = CleanedDataFormValidation(form_class=CourseCreateForm) validation_errors = validation.is_valid(bundle) if validation_errors: raise ImmediateHttpResponse(response=self.error_response( bundle.request, validation_errors)) # ETAPA 2 - Efetuando operações no EDX # ------------------------------------ course_create(bundle.data) # Adicionando ``resource_uri`` bundle.data['resource_uri'] = reverse('api_dispatch_detail', kwargs={ 'api_name': CourseResource._meta.api_name, 'resource_name': CourseResource._meta.resource_name, 'course_id_solaredx': course_id_encoder(bundle.data['course_id'])}) return self.create_response(request, bundle, response_class=http.HttpCreated)
def delete_detail(self, request, **kwargs): " Deleta um curso. " # ETAPA 1 - Desserialização e validação dos dados recebidos # --------------------------------------------------------- course_id = course_id_decoder(kwargs['course_id_solaredx']) deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = Bundle(data=dict_strip_unicode_keys(deserialized), request=request) bundle.data['course_id'] = course_id validation = CleanedDataFormValidation(form_class=CourseDeleteForm) validation_errors = validation.is_valid(bundle) if validation_errors: raise ImmediateHttpResponse(response=self.error_response( bundle.request, validation_errors)) # ETAPA 2 - Efetuando operações no EDX # ------------------------------------ course_delete(course_id) return http.HttpNoContent()
class Meta: resource_name = 'engagements' list_allowed_methods = ['get', 'post'] # disabled delete for /id/ detail_allowed_methods = ['get', 'post', 'put'] queryset = Engagement.objects.all() include_resource_uri = True filtering = { 'id': ALL, 'active': ALL, 'eng_type': ALL, 'target_start': ALL, 'target_end': ALL, 'requester': ALL, 'report_type': ALL, 'updated': ALL, 'threat_model': ALL, 'api_test': ALL, 'pen_test': ALL, 'status': ALL, 'product': ALL, } authentication = DojoApiKeyAuthentication() authorization = DjangoAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=EngForm2)
def test_init(self): self.assertRaises(ImproperlyConfigured, CleanedDataFormValidation) try: CleanedDataFormValidation(form_class=NoteForm) except Exception: self.fail("Initialization failed when it should have succeeded.")
class Meta(MarketplaceResource.Meta): always_return_data = True authorization = Authorization() list_allowed_methods = ['post'] object_class = dict resource_name = 'login' validation = CleanedDataFormValidation(form_class=LoginForm)
class Meta: resource_name = 'findings' queryset = Finding.objects.select_related("test") # deleting of findings is not allowed via UI or API. # Admin interface can be used for this. list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put'] include_resource_uri = True filtering = { 'id': ALL, 'title': ALL, 'date': ALL, 'severity': ALL, 'description': ALL, 'mitigated': ALL, 'endpoint': ALL, 'test': ALL, 'active': ALL, 'verified': ALL, 'false_p': ALL, 'reporter': ALL, 'url': ALL, } authentication = DojoApiKeyAuthentication() authorization = DjangoAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=FindingForm)
class Meta: resource_name = 'products' # disabled delete. Should not be allowed without fine authorization. list_allowed_methods = ['get', 'post'] # only allow get for lists detail_allowed_methods = ['get', 'post', 'put'] queryset = Product.objects.all().order_by('name') ordering = [ 'name', 'id', 'description', 'findings_count', 'created', 'product_type_id' ] excludes = [ 'tid', 'manager', 'prod_manager', 'tech_contact', 'updated' ] include_resource_uri = True filtering = { 'id': ALL, 'name': ALL, 'prod_type': ALL, 'created': ALL, 'findings_count': ALL } authentication = TrackerApiKeyAuthentication() authorization = UserProductsOnlyAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=ProductForm)
class Meta: queryset = Space.objects.all() authentication = Authentication() # authentication = MultiAuthentication( # BasicAuthentication, ApiKeyAuthentication()) authorization = Authorization() # authorization = DjangoAuthorization() validation = CleanedDataFormValidation(form_class=SpaceForm) resource_name = 'space' fields = [ 'access_protocol', 'last_verified', 'location_set', 'path', 'size', 'used', 'uuid', 'verified' ] list_allowed_methods = ['get'] detail_allowed_methods = ['get'] detail_uri_name = 'uuid' always_return_data = True filtering = { 'access_protocol': ALL, 'path': ALL, 'size': ALL, 'used': ALL, 'uuid': ALL, 'verified': ALL, }
class Meta(MarketplaceResource.Meta): resource_name = 'global' authentication = OptionalOAuthAuthentication() authorization = Authorization() detail_allowed_methods = ['get'] list_allowed_methods = [] object_class = GenericObject validation = CleanedDataFormValidation(form_class=GlobalStatsForm)
class Meta(MarketplaceResource.Meta): always_return_data = True authentication = OptionalOAuthAuthentication() authorization = Authorization() detail_allowed_methods = [] list_allowed_methods = ['post'] object_class = dict resource_name = 'test' validation = CleanedDataFormValidation(form_class=TestInstall)
class Meta(MarketplaceResource.Meta): always_return_data = True authentication = (SharedSecretAuthentication(), OAuthAuthentication()) authorization = Authorization() detail_allowed_methods = [] list_allowed_methods = ['post'] object_class = GenericObject resource_name = 'prepare' validation = CleanedDataFormValidation(form_class=PrepareForm)
class Meta: queryset = Comment.objects.all() resource_name = 'tribs/comments' ordering = ['comment_pub_date'] allowed_methods = ['get', 'post', 'delete'] filtering = {'trib_id': ALL_WITH_RELATIONS} authorization = CommentAuthorization() authentication = SessionAuthentication() validation = CleanedDataFormValidation(form_class=CommentForm) cache = NoCache()
class Meta: queryset = User.objects.all() resource_name = 'user' serializer = SafeSerializer() authorization = Authorization() authentication = DeveloperApiKeyAuthentication() validation = CleanedDataFormValidation(form_class=UserForm) list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'put', 'delete'] excludes = ['username', 'password']
def test_is_valid(self): valid = CleanedDataFormValidation(form_class=NoteForm) bundle = Bundle() self.assertEqual(valid.is_valid(bundle), { 'is_active': [u'This field is required.'], 'slug': [u'This field is required.'], '__all__': [u'Having no content makes for a very boring note.'], 'title': [u'This field is required.'], }) bundle = Bundle(data={ 'title': 'Foo.', 'slug': '123456789012345678901234567890123456789012345678901234567890', 'content': '', 'is_active': True, }) self.assertEqual(valid.is_valid(bundle), { 'slug': [u'Ensure this value has at most 50 characters (it has 60).'], '__all__': [u'Having no content makes for a very boring note.'], }) bundle = Bundle(data={ 'title': 'Foo.', 'slug': 'bar', 'content': '', 'is_active': True, }) self.assertEqual(valid.is_valid(bundle), { '__all__': [u'Having no content makes for a very boring note.'], }) bundle = Bundle(data={ 'title': 'Foo.', 'slug': 'bar', 'content': 'This! Is! CONTENT!', 'is_active': True, }) self.assertEqual(valid.is_valid(bundle), {}) # NOTE: Bundle data is modified! self.assertEqual(bundle.data['title'], u'FOO.')
class Meta: resource_name = "split_transaction" queryset = SplitTransaction.objects.all()\ .annotate(total_value=Sum('transactions__value'))\ .annotate(installments=Count('transactions')) always_return_data = True authentication = MultiAuthentication(SessionAuthentication(), BasicAuthentication()) authorization = UserObjectsOnlyAuthorization() validation = CleanedDataFormValidation( form_class=SplitTransactionApiForm) list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get']
class Meta(MarketplaceResource.Meta): authentication = OptionalOAuthAuthentication() authorization = AnonymousReadOnlyAuthorization( authorizer=PermissionAuthorization('ProductIcon', 'Create')) detail_allowed_methods = ['get'] fields = ['ext_url', 'ext_size', 'size'] filtering = { 'ext_url': 'exact', 'ext_size': 'exact', 'size': 'exact', } list_allowed_methods = ['get', 'post'] queryset = ProductIcon.objects.filter() resource_name = 'product/icon' validation = CleanedDataFormValidation(form_class=ProductIconForm)
class Meta: always_return_data = True queryset = Pin.objects.all() resource_name = 'pin' include_resource_uri = False allowed_methods = ['get', 'post', 'delete'] filtering = { 'published': ['gt'], 'submitter': ALL_WITH_RELATIONS, 'favorites': ALL_WITH_RELATIONS, 'popularity': ALL, 'tags': ALL, } validation = CleanedDataFormValidation(form_class=PinForm) #ordering = ['popularity'] authorization = DjangoAuthorization()
class Meta: resource_name = 'stub_findings' queryset = Stub_Finding.objects.select_related("test") # deleting of findings is not allowed via UI or API. # Admin interface can be used for this. list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put'] include_resource_uri = True filtering = { 'id': ALL, 'title': ALL, 'date': ALL, 'severity': ALL, 'description': ALL, } authentication = SessionAuthentication() authorization = UserProductsOnlyAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=StubFindingForm)
class Meta: resource_name = 'scan_settings' queryset = ScanSettings.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'put', 'post', 'delete'] include_resource_uri = True filtering = { 'id': ALL, 'date': ALL, 'user': ALL, 'frequency': ALL, 'product': ALL, 'addresses': ALL } authentication = DojoApiKeyAuthentication() authorization = UserScanSettingsAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=ScanSettingsForm)
class Meta: resource_name = 'tests' list_allowed_methods = ['get', 'post'] # disabled delete. Should not be allowed without fine authorization. detail_allowed_methods = ['get', 'post', 'put'] queryset = Test.objects.all().order_by('target_end') include_resource_uri = True filtering = { 'id': ALL, 'test_type': ALL, 'target_start': ALL, 'target_end': ALL, 'notes': ALL, 'percent_complete': ALL, 'actual_time': ALL } authentication = DojoApiKeyAuthentication() authorization = DjangoAuthorization() serializer = Serializer(formats=['json']) validation = CleanedDataFormValidation(form_class=TestForm)
def test_is_valid(self): valid = CleanedDataFormValidation(form_class=NoteForm) bundle = Bundle() self.assertEqual( valid.is_valid(bundle), { 'is_active': [u'This field is required.'], 'slug': [u'This field is required.'], '__all__': [u'Having no content makes for a very boring note.'], 'title': [u'This field is required.'], }) bundle = Bundle( data={ 'title': 'Foo.', 'slug': '123456789012345678901234567890123456789012345678901234567890', 'content': '', 'is_active': True, }) self.assertEqual( valid.is_valid(bundle), { 'slug': [u'Ensure this value has at most 50 characters (it has 60).'], '__all__': [u'Having no content makes for a very boring note.'], }) bundle = Bundle(data={ 'title': 'Foo.', 'slug': 'bar', 'content': '', 'is_active': True, }) self.assertEqual(valid.is_valid(bundle), { '__all__': [u'Having no content makes for a very boring note.'], }) bundle = Bundle( data={ 'title': 'Foo.', 'slug': 'bar', 'content': 'This! Is! CONTENT!', 'is_active': True, }) self.assertEqual(valid.is_valid(bundle), {}) # NOTE: Bundle data is modified! self.assertEqual(bundle.data['title'], u'FOO.')
class CmntResource(ModelResource): user = fields.ToOneField('pinry.api.api.UserResource', 'user', full=True) site_id = fields.CharField(attribute='site_id') content_object = GenericForeignKeyField({ Pin: PinResource, }, 'content_object') username = fields.CharField(attribute='user__username', null=True) user_id = fields.CharField(attribute='user__id', null=True) validation = CleanedDataFormValidation(form_class=CommentForm) class Meta: always_return_data = True queryset = Comment.objects.all() resource_name = 'cmnt' include_resource_uri = False allowed_methods = [ 'get', 'post', 'delete' ] #TODO: I should be using put for comment edits.... #fields, object_pk & content_type_id are REQUIRED for generic foreign key fields = ['id', 'comment', 'submit_date'] #excludes = ["ip_address", "is_public", "is_removed", "user_email", "user_name", "user_url"] #other fields: "comment", "content_type_id", "id", "object_pk", "submit_date", "user_id", "username" filtering = { 'object_pk': ALL_WITH_RELATIONS, 'content_type': ALL_WITH_RELATIONS, } #authentication = BasicAuthentication() authorization = DjangoAuthorization() ''' def dehydrate(self, bundle): #dehydrate follows for only favorites for f in bundle.data['follows'][:]: if f.data['id'] == None: bundle.data['follows'].remove(f) return bundle ''' def alter_list_data_to_serialize(self, request, bundle): for obj in bundle['objects']: del obj.data['user'] del obj.data['site_id'] #del obj.data['object_pk'] #del obj.data['content_type_id'] del obj.data['content_object'] return bundle def alter_detail_data_to_serialize(self, request, bundle): del bundle.data['user'] del bundle.data['site_id'] del bundle.data['content_object'] #DO NOT BLOCK THE BELOW. they need to be serialized for object creation with GFK! #del bundle.data['object_pk'] #del bundle.data['content_type_id'] return bundle def determine_format(self, request): return "application/json" def obj_create(self, bundle, **kwargs): print '----obj_create------' #content_type='/api/v1/contrib/contenttype/'+bundle.data['content_type_id']+'/' #content_object_url = '/api/v1/pin/'+bundle.data['object_pk']+'/' # if id make sure the orig submitter remains in case of admin edit. id = bundle.data.get('id', None) if id: comment = Comment.objects.get(pk__exact=int(id)) user = comment.user else: user = bundle.request.user bundle = super(CmntResource, self).obj_create(bundle, user=user) return bundle
class Meta: queryset = Drink.objects.all() authorization = Authorization() validation = CleanedDataFormValidation(form_class=DrinkForm)
class Meta: queryset = Category.objects.all() authorization = Authorization() validation = CleanedDataFormValidation(form_class=CategoryForm)
def validate_post(self, bundle, request): form = CleanedDataFormValidation(form_class=CreateAgoraForm) return form.is_valid(bundle, request)
def validate_put(self, bundle, request): form = CleanedDataFormValidation(form_class=AgoraAdminForm) return form.is_valid(bundle, request)
def test_init_form_class_provided(self): try: CleanedDataFormValidation(form_class=NoteForm) except Exception: self.fail("Initialization failed when it should have succeeded.")