def generic_base_check(self, object_list, bundle): """ Returns False if either: a) if the `object_list.model` doesn't have a `_meta` attribute b) the `bundle.request` object doesn have a `user` attribute """ klass = self.base_checks(bundle.request, object_list.model) if klass is False: raise ImmediateHttpResponse( HttpForbidden("You are not allowed to access that resource.")) return True
def safe_get(self, request, **kwargs): filters = self.remove_api_resource_names(kwargs) try: del (filters['index']) except KeyError: pass try: return self.parent.cached_obj_get(request=request, **filters) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=HttpGone())
def dispatch_list(self, request, **kwargs): try: return super(UserDomainsResource, self).dispatch_list(request, **kwargs) except ImmediateHttpResponse as immediate_http_response: if isinstance(immediate_http_response.response, HttpUnauthorized): raise ImmediateHttpResponse(response=HttpUnauthorized( content='Username or API Key is incorrect', content_type='text/plain')) else: raise
def get_list(self, request, **kwargs): if request.user.is_authenticated() and request.user.role in [0,1]: return super(UserResource, self).get_list(request, **kwargs) else: if request.user.is_authenticated(): kwargs["pk"] = request.user.pk return super(UserResource, self).get_detail(request, **kwargs) else: data_res = {'status': 'false', 'message': "obj not found"} response = self.error_response(request, data_res, response_class=HttpBadRequest) raise ImmediateHttpResponse(response=response)
def dispatch(self, request_type, request, **kwargs): if toggles.API_BLACKLIST.enabled_for_request(request): msg = ("API access has been temporarily cut off due to too many " "requests. To re-enable, please contact support.") raise ImmediateHttpResponse(HttpResponse( json.dumps({"error": msg}), content_type="application/json", status=401)) if request.user.is_superuser or domain_has_privilege(request.domain, privileges.API_ACCESS): if isinstance(self, DomainSpecificResourceMixin): track_workflow(request.user.username, "API Request", properties={ 'domain': request.domain, 'is_dimagi': request.user.username.endswith('@dimagi.com'), }) return super(HqBaseResource, self).dispatch(request_type, request, **kwargs) else: raise ImmediateHttpResponse(HttpResponse( json.dumps({"error": "Your current plan does not have access to this feature"}), content_type="application/json", status=401))
def obj_create(self, bundle, **kwargs): if bundle.request.user: form = SetPasswordForm(bundle.request.user, data=bundle.data) if form.is_valid(): bundle.obj = form.save() else: raise ImmediateHttpResponse(response=self.error_response( bundle.request, {'errors': form.errors})) return bundle
def disable(self, request, **kwargs): ''' Disable the currently authenticated user ''' if request.user.is_anonymous(): raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed()) request.user.is_active = False request.user.save() auth_logout(request) return self.create_response(request, dict(status="success"))
def obj_create(self, bundle, **kwargs): twitter_handle = bundle.data['twitter_handle'] try: person = Person.objects.get(twitter_handle=twitter_handle) except Person.DoesNotExist: pass else: raise ImmediateHttpResponse(HttpResponseRedirect("/api/v1/person/%s/" % person.twitter_handle)) return super(PersonResource, self).obj_create(bundle, **kwargs)
def obj_create(self, bundle, request=None, **kwargs): print 'add_user>>>>>', bundle user_profile.objects.create(user_name=bundle.data['username'], user_pswrd=bundle.data['paswrd'], mobile_no=bundle.data['mob_no'], city=bundle.data['city']) raise ImmediateHttpResponse(response=HttpResponse( content=json.dumps('success'), content_type="application/json; charset=UTF-8"))
def dehydrate_response(self, bundle): ## see what the context request is context_request = bundle.request.GET['request'] if context_request == EnvrionmentContextResource.PEOPLE_COUNT: environment = bundle.obj environment_people_count = UserContext.objects.filter(currentEnvironment = environment).count() return environment_people_count else: raise ImmediateHttpResponse(response=http.HttpNotImplemented())
def method_check(self, request, allowed=None): if allowed is None: allowed = [] request_method = request.method.lower() allows = ','.join(map(lambda s: s.upper(), allowed)) if request_method == 'options': response = HttpResponse(allows) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = 'Content-Type' response['Allow'] = allows raise ImmediateHttpResponse(response=response) if not request_method in allowed: response = http.HttpMethodNotAllowed(allows) response['Allow'] = allows raise ImmediateHttpResponse(response=response) return request_method
def assert_current_state_is(from_state): if type(from_state) is list: wrong_status = booking.state not in from_state else: wrong_status = booking.state != from_state if wrong_status: raise ImmediateHttpResponse(response=error( "Need to be in state %s to switch to state %s" % (from_state, booking.state)))
def userprofile(self, request, *args, **kwargs): fields = copy.copy(self._meta.fields) try: target_user = User.objects.get(pk=kwargs['pk']) except User.DoesNotExist: raise ImmediateHttpResponse(HttpNotFound()) else: if target_user == request.user: fields += ['first_name', 'last_name'] data = {k: getattr(target_user, k) for k in fields} return self.create_response(request, data)
def obj_get(self, request=None, **kwargs): """ Returns mongodb document from provided id. """ document = Document.objects.get(_id=ObjectId(kwargs.get("pk"))) if request is not None and not document.is_visible( user_id=request.user.id): raise ImmediateHttpResponse(response=http.HttpUnauthorized()) return document
def obj_create(self, bundle, **kwargs): try: if not bundle.request.user.is_staff: raise Unauthorized() except Unauthorized as e: self.unauthorized_result(e) self.is_valid(bundle) if bundle.errors: raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors)) url, clusters, headers = bundle.data['url'], bundle.data['clusters'], bundle.data.get('headers') purger = VarnishPurger() if not isinstance(clusters, list): clusters = [clusters] servers = ServerExtractor().extract_servers_by_clusters(LogicalCluster.objects.filter(name__in=clusters)) purger_result = purger.purge_url(url, servers, headers) if len(purger_result.get("error")) > 0: raise ImmediateHttpResponse(self.create_json_response(purger_result, HttpApplicationError)) raise ImmediateHttpResponse(self.create_json_response(purger_result, HttpResponse))
def obj_delete(self, bundle, **kwargs): try: scheme_id = kwargs['pk'] scheme = TemplateScheme.objects.get(pk=scheme_id) template = TaskTemplate.objects.get(pipeline_template=scheme.template) except Exception: raise BadRequest('scheme or template does not exist') business = get_business_for_user(bundle.request.user, ['manage_business']) if not business.filter(cc_id=template.business.cc_id).exists(): raise ImmediateHttpResponse(HttpResponseForbidden('you have no permission to make such operation')) return super(TemplateSchemeResource, self).obj_delete(bundle, **kwargs)
def dispatch(self, request_type, request, **kwargs): if toggles.API_BLACKLIST.enabled_for_request(request): msg = ("API access has been temporarily cut off due to too many " "requests. To re-enable, please contact support.") raise ImmediateHttpResponse( HttpResponse(json.dumps({"error": msg}), content_type="application/json", status=401)) if request.user.is_superuser or domain_has_privilege( request.domain, privileges.API_ACCESS): return super(HqBaseResource, self).dispatch(request_type, request, **kwargs) else: raise ImmediateHttpResponse( HttpResponse(json.dumps({ "error": "Your current plan does not have access to this feature" }), content_type="application/json", status=401))
def raise_not_acceptable_error(message): """ Raises Http406 error with message. :param message: Error message :return: None """ class HttpMethodNotAcceptable(HttpResponse): status_code = 406 raise ImmediateHttpResponse(HttpMethodNotAcceptable(message))
def is_authenticated(self, request): """ An override of the tastypie Authentication to accept an iterator of Authentication methods. If so it will go through in order, when one passes, it will use that. Any authentication method can still return a HttpResponse to break out of the loop if they desire. """ for auth in self._auths(): auth_result = auth.is_authenticated(request) if isinstance(auth_result, http.HttpResponse): raise ImmediateHttpResponse(response=auth_result) if auth_result: log.info('Logged in using %s' % auth.__class__.__name__) return raise ImmediateHttpResponse(response=http.HttpUnauthorized())
def apply_filters(self, request, applicable_filters): """An ORM-specific implementation of ``apply_filters``. The default simply applies the ``applicable_filters`` as ``**kwargs``, but should make it possible to do more advanced things. """ # List units only when a filter criterion was provided. if not applicable_filters: raise ImmediateHttpResponse(response=HttpNotImplemented()) return super(UnitResource, self).apply_filters(request, applicable_filters)
def dispatch(self, request_type, request, **kwargs): if not toggles.ODATA.enabled_for_request(request): raise ImmediateHttpResponse( response=HttpResponseNotFound('Feature flag not enabled.')) self.config_id = kwargs['config_id'] with TimingContext() as timer: response = super(ODataFormResource, self).dispatch(request_type, request, **kwargs) record_feed_access_in_datadog(request, self.config_id, timer.duration, response) return response
def obj_get_list(self, bundle, **kwargs): domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden('You are not allowed to get list of case types for this domain') ) case_types = get_case_types_for_domain_es(domain) results = [CaseType(case_type=case_type) for case_type in case_types] return results
def method_check(self, request, allowed=None): if allowed is None: allowed = [] request_method = request.method.lower() allows = ','.join([x.upper() for x in allowed if x]) if request_method == 'options': response = HttpResponse(allows) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' response['Allow'] = allows raise ImmediateHttpResponse(response=response) if request_method not in allowed: response = http.HttpMethodNotAllowed(allows) response['Allow'] = allows raise ImmediateHttpResponse(response=response) return request_method
def authorized_update_detail(self, object_list, bundle): """ Handles checking of permissions to see if the user has authorization to PUT this resource. Over-riding version from parent class because we want to allow raising NotFound errors. """ try: auth_result = self._meta.authorization.update_detail( object_list, bundle) if auth_result is not True: raise Unauthorized() except Unauthorized as e: #self.unauthorized_result(e) raise ImmediateHttpResponse(response=HttpResponseForbidden()) except NotFound as e: raise ImmediateHttpResponse(response=HttpResponseNotFound()) return auth_result
def obj_create(self, bundle, **kwargs): if Location.objects.filter(address=bundle.data['address']).exists(): errors = {'error': 'Marker with this address already exist'} raise ImmediateHttpResponse( response=HttpResponse(content=json.dumps(errors), status=409)) manager = GoogleFusionTableManager(table_id=self.table_id) # TODO: handle error from Manager manager.create(address=bundle.data['address']) return super(LocationResource, self).obj_create(bundle, **kwargs)
def dispatch(self, request_type, request, *args, **kwargs): try: return super(ResourceMixin, self).dispatch( request_type, request, *args, **kwargs ) except (MiddlewareError, ServiceFailed), e: raise ImmediateHttpResponse( response=self.error_response(request, { 'error_message': unicode(e), }) )
def obj_create(self, bundle, **kwargs): if hasattr(bundle.request.user, 'owner'): if hasattr(self._meta.object_class, 'source'): kwargs['source'] = bundle.request.user.owner.source if hasattr(self._meta.object_class, 'owner'): kwargs['owner'] = bundle.request.user.owner if hasattr(self._meta.object_class, 'event'): kwargs['event__source'] = bundle.request.user.owner.source return super(Content, self).obj_create(bundle, **kwargs) raise ImmediateHttpResponse(response=HttpForbidden())
def throttle_check(self, request): """Override throttle check to throttle differently on GET and POST. """ identifier = self._meta.authentication.get_identifier(request) if request.method == 'POST': if self._meta.post_throttle.should_be_throttled(identifier): raise ImmediateHttpResponse(response=HttpTooManyRequests()) else: return super(CollMapResource, self).throttle_check(request)
def obj_get(self, request=None, **kwargs): # Until the perms branch lands, this is the only way to lock # permissions down on gets, since the object doesn't actually # get passed through to OwnerAuthorization. try: obj = FileUpload.objects.get(pk=kwargs['pk']) except FileUpload.DoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound()) log.info('Validation retreived: %s' % obj.pk) return obj
def dispatch(self, request_type, request, **kwargs): if not domain_has_privilege(request.domain, privileges.ODATA_FEED): raise ImmediateHttpResponse( response=HttpResponseNotFound('Feature flag not enabled.')) self.config_id = kwargs['config_id'] self.table_id = int(kwargs.get('table_id', 0)) with TimingContext() as timer: response = super(BaseODataResource, self).dispatch(request_type, request, **kwargs) record_feed_access_in_datadog(request, self.config_id, timer.duration, response) return response