コード例 #1
0
 def is_authenticated(self, request):
     '''Determines whether a given HTTP request is authenticated or
     not, and sets the requests user field if it is.'''
     token = None
     # get a token if this is a GET
     if request.GET and 'token' in request.GET:
         token = request.GET['token']
     # get a token if this is a POST
     if request.POST and 'token' in request.POST:
         token = request.POST['token']
     # translate mime-types in the request if this is a mime
     # message
     try:
         translate_mime(request)
     except MimerDataException:
         pass
     # check if there's a token in the mime data
     if ( hasattr(request, 'data') and
          request.data and
          'token' in request.data ):
         token = request.data['token']
     if token:
         try:
             token = AuthToken.objects.get(auth_token = token)
             if token.enabled:
                 request.user = token.user
                 return True
         except (ObjectDoesNotExist, MultipleObjectsReturned):
             pass
     return False
コード例 #2
0
ファイル: django.py プロジェクト: cloudbase/maas
def parse_headers_and_body_with_mimer(headers, body):
    """Use piston's Mimer functionality to handle the content.

    :return: The value of 'request.data' after using Piston's translate_mime on
        the input.
    """
    # JAM 2012-10-09 Importing emitters has a side effect of registering mime
    #   type handlers with utils.translate_mime. So we must import it, even
    #   though we don't use it.  However, piston loads Django's QuerySet code
    #   which fails if you don't have a settings.py available. Which we don't
    #   during 'test.pserv'. So we import this late.
    from piston import emitters
    ignore_unused(emitters)
    from piston.utils import translate_mime

    environ = {'wsgi.input': BytesIO(body)}
    for name, value in headers.items():
        environ[name.upper().replace('-', '_')] = value
    environ['REQUEST_METHOD'] = 'POST'
    environ['SCRIPT_NAME'] = ''
    environ['PATH_INFO'] = ''
    # Django 1.6 needs DJANGO_SETTINGS_MODULE to be defined
    # when importing WSGIRequest.
    os.environ['DJANGO_SETTINGS_MODULE'] = 'maas.development'
    from django.core.handlers.wsgi import WSGIRequest
    request = WSGIRequest(environ)
    translate_mime(request)
    return request.data
コード例 #3
0
ファイル: django.py プロジェクト: binoymvas/contribution
def parse_headers_and_body_with_mimer(headers, body):
    """Use piston's Mimer functionality to handle the content.

    :return: The value of 'request.data' after using Piston's translate_mime on
        the input.
    """
    # JAM 2012-10-09 Importing emitters has a side effect of registering mime
    #   type handlers with utils.translate_mime. So we must import it, even
    #   though we don't use it.  However, piston loads Django's QuerySet code
    #   which fails if you don't have a settings.py available. Which we don't
    #   during 'test.cluster'. So we import this late.
    from piston import emitters
    emitters  # Imported for side-effects.
    from piston.utils import translate_mime

    environ = {'wsgi.input': BytesIO(body)}
    for name, value in headers.items():
        environ[name.upper().replace('-', '_')] = value
    environ['REQUEST_METHOD'] = 'POST'
    environ['SCRIPT_NAME'] = ''
    environ['PATH_INFO'] = ''
    # Django 1.6 needs DJANGO_SETTINGS_MODULE to be defined
    # when importing WSGIRequest.
    os.environ['DJANGO_SETTINGS_MODULE'] = 'maas.development'
    from django.core.handlers.wsgi import WSGIRequest
    request = WSGIRequest(environ)
    translate_mime(request)
    return request.data
コード例 #4
0
ファイル: handlers.py プロジェクト: byronmccollum/djeep
  def brew(self, request, id):
    """Redeploy a cluster."""
    cluster = models.Cluster.objects.get(pk=id)
    hosts = models.Host.objects.filter(cluster=cluster)

    # TODO(termie): A bit of a hack because I don't want to replicate the
    #               entire __call__ method in piston's Resource.
    try:
      utils.translate_mime(request)
    except utils.MimerDataException:
      return rc.BAD_REQUEST

    request.data = getattr(request, 'data', None)
    if cluster.claim and (not request.data or
                          cluster.claim != request.data.get('claim')):
      resp = rc.FORBIDDEN
      resp.content = ('FORBIDDEN: This cluster has been claimed: %s'
                      % cluster.claim)
      return resp

    for host in hosts:
      host.local_boot =  False
      host.save()
      remote.pxe_reboot(host)

    return hosts
コード例 #5
0
ファイル: handlers.py プロジェクト: hughsaunders/djeep
    def brew(self, request, id):
        """Redeploy a cluster."""
        cluster = models.Cluster.objects.get(pk=id)
        hosts = models.Host.objects.filter(cluster=cluster)

        # TODO(termie): A bit of a hack because I don't want to replicate the
        #               entire __call__ method in piston's Resource.
        try:
            utils.translate_mime(request)
        except utils.MimerDataException:
            return rc.BAD_REQUEST

        request.data = getattr(request, 'data', None)
        if cluster.claim and (not request.data
                              or cluster.claim != request.data.get('claim')):
            resp = rc.FORBIDDEN
            resp.content = ('FORBIDDEN: This cluster has been claimed: %s' %
                            cluster.claim)
            return resp

        for host in hosts:
            host.local_boot = False
            host.save()
            remote.pxe_reboot(host)

        return hosts
コード例 #6
0
ファイル: handlers.py プロジェクト: jfardello/Steamer
 def delete(self, request, serviceid=None):
     try:
         translate_mime(request)
         if not serviceid:
             serviceid = request.data.get('service')
         return self._manage(request, serviceid=serviceid, action='remove')
     except MimerDataException:
         return rc.BAD_REQUEST
コード例 #7
0
 def delete(self, request, serviceid=None):
     try:
         translate_mime(request)
         if not serviceid:
             serviceid = request.data.get('service')
         return self._manage(request, serviceid=serviceid, action='remove')
     except MimerDataException:
         return rc.BAD_REQUEST
コード例 #8
0
ファイル: resources.py プロジェクト: gage/proto
    def __call__(self, request, *args, **kwargs):
        rm = request.method.upper()
        handler, anonymous = self.handler, self.handler.is_anonymous
        
        if rm == 'PUT' and request.META['CONTENT_TYPE']=="application/json":
            rm = request.method = 'POST'
        
        # Translate nested datastructs into `request.data` here.
        if rm == 'POST':
            try:
                translate_mime(request)
            except MimerDataException:
                return rc.BAD_REQUEST
            if not hasattr(request, 'data'):
                request.data = request.POST
        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)

        meth = getattr(handler, self.callmap.get(rm, ''), None)
        if not meth:
            raise Http404

        # Clean up the request object a bit, since we might
        # very well have `oauth_`-headers in there, and we
        # don't want to pass these along to the handler.

        request = self.cleanup_request(request)

        try:
            # The verified process of new api is all in process_request
            request = process_request(handler, request, *args, **kwargs)
            raw_response = meth(request, *args, **kwargs)
            # An implicit protocal for deliver info from handler
            if type(raw_response)==dict and raw_response.has_key('_info') and raw_response.has_key('_response'):
                if request.REQUEST.get('raw'):
                    result = raw_response['_response']
                else:
                    result = {
                        'success': True,
                        'response': raw_response['_response'],
                        'info': raw_response['_info'],
                    }
            else:
                if request.REQUEST.get('raw'):
                    result = raw_response
                else:
                    result = {
                        'success': True,
                        'response': raw_response,
                        'info': {}
                    }
        except Exception, e:
            result = self.error_handler(e, request, meth)
コード例 #9
0
ファイル: resource.py プロジェクト: ekohl/django-piston
    def __call__(self, request, *args, **kwargs):
        """
        NB: Sends a `Vary` header so we don't cache requests
        that are different (OAuth stuff in `Authorization` header.)
        """
        rm = request.method.upper()

        # Django's internal mechanism doesn't pick up
        # PUT request, so we trick it a little here.
        if rm == "PUT":
            coerce_put_post(request)

        actor, anonymous = self.authenticate(request, rm)

        if anonymous is CHALLENGE:
            return actor()
        else:
            handler = actor

        # Translate nested datastructs into `request.data` here.
        if rm in ('POST', 'PUT'):
            try:
                translate_mime(request)
            except MimerDataException:
                return rc.BAD_REQUEST
            if not hasattr(request, 'data'):
                if rm == 'POST':
                    request.data = request.POST
                else:
                    request.data = request.PUT

        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)

        meth = getattr(handler, self.callmap.get(rm, ''), None)
        if not meth:
            raise Http404

        # Support emitter both through (?P<emitter_format>) and ?format=emitter.
        em_format = self.determine_emitter(request, *args, **kwargs)

        kwargs.pop('emitter_format', None)

        # Clean up the request object a bit, since we might
        # very well have `oauth_`-headers in there, and we
        # don't want to pass these along to the handler.
        request = self.cleanup_request(request)

        try:
            result = meth(request, *args, **kwargs)
        except Exception, e:
            result = self.error_handler(e, request, meth, em_format)
コード例 #10
0
    def __call__(self, request, *args, **kwargs):
        """
        NB: Sends a `Vary` header so we don't cache requests
        that are different (OAuth stuff in `Authorization` header.)
        """
        rm = request.method.upper()

        # Django's internal mechanism doesn't pick up
        # PUT request, so we trick it a little here.
        if rm == "PUT":
            coerce_put_post(request)

        actor, anonymous = self.authenticate(request, rm)

        if anonymous is CHALLENGE:
            return actor()
        else:
            handler = actor

        # Translate nested datastructs into `request.data` here.
        if rm in ('POST', 'PUT'):
            try:
                translate_mime(request)
            except MimerDataException:
                return rc.BAD_REQUEST
            if not hasattr(request, 'data'):
                if rm == 'POST':
                    request.data = request.POST
                else:
                    request.data = request.PUT

        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)

        meth = getattr(handler, self.callmap.get(rm, ''), None)
        if not meth:
            raise Http404

        # Support emitter both through (?P<emitter_format>) and ?format=emitter.
        em_format = self.determine_emitter(request, *args, **kwargs)

        kwargs.pop('emitter_format', None)

        # Clean up the request object a bit, since we might
        # very well have `oauth_`-headers in there, and we
        # don't want to pass these along to the handler.
        request = self.cleanup_request(request)

        try:
            result = meth(request, *args, **kwargs)
        except Exception, e:
            result = self.error_handler(e, request, meth, em_format)
コード例 #11
0
ファイル: handlers.py プロジェクト: jfardello/Steamer
 def delete(self, request):
     try:
         translate_mime(request)
         if request.content_type and request.data.get('host'):
             form = RemoveHostForm(request.data)
             if form.is_valid():
                 try:
                     h = Host.objects.get(pk=request.data.get('host'))
                     h.delete()
                     return rc.DELETED
                 except Host.DoesNotExist:
                     return rc.BAD_REQUEST
             else:
                 #this is how we tell jQuery about the form errors.
                 resp = rc.UNPROCESSABLE 
                 resp.write(dict((k, map(unicode, v))
                    for (k,v) in form.errors.iteritems()))
                 return resp
         else:
             return rc.BAD_REQUEST
     except MimerDataException:
         return rc.BAD_REQUEST
コード例 #12
0
 def delete(self, request):
     try:
         translate_mime(request)
         if request.content_type and request.data.get('host'):
             form = RemoveHostForm(request.data)
             if form.is_valid():
                 try:
                     h = Host.objects.get(pk=request.data.get('host'))
                     h.delete()
                     return rc.DELETED
                 except Host.DoesNotExist:
                     return rc.BAD_REQUEST
             else:
                 #this is how we tell jQuery about the form errors.
                 resp = rc.UNPROCESSABLE
                 resp.write(
                     dict((k, map(unicode, v))
                          for (k, v) in form.errors.iteritems()))
                 return resp
         else:
             return rc.BAD_REQUEST
     except MimerDataException:
         return rc.BAD_REQUEST
コード例 #13
0
    def __call__(self, request, *args, **kwargs):
        rm = request.method.upper()

        if rm == "PUT":
            coerce_put_post(request)

        actor, anonymous = self.authenticate(request, rm)

        if anonymous is CHALLENGE:
            return actor()
        else:
            handler = actor

        if rm in ('POST', 'PUT'):
            try:
                translate_mime(request)
            except MimerDataException:
                return rc.BAD_REQUEST
            if not hasattr(request, 'data'):
                if rm == 'POST':
                    request.data = request.POST
                else:
                    request.data = request.PUT

        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)

        meth = getattr(handler, self.callmap.get(rm, ''), None)
        if not meth:
            raise Http404

        em_format = self.determine_emitter(request, *args, **kwargs)
        kwargs.pop('emitter_format', None)

        request = self.cleanup_request(request)

        try:
            result = meth(request, *args, **kwargs)
        except ValueError:
            result = rc.BAD_REQUEST
            result.content = 'Invalid arguments'

        try:
            emitter, ct = Emitter.get(em_format)
            fields = handler.fields
            if hasattr(handler, 'list_fields') and isinstance(
                    result, (list, tuple, QuerySet)):
                fields = handler.list_fields
        except ValueError:
            result = rc.BAD_REQUEST
            result.content = "Invalid output format specified '%s'." % em_format
            return result

        status_code = 200

        if isinstance(result, HttpResponse) and not result._is_string:
            status_code = result.status_code
            result = result._container

        srl = emitter(result, typemapper, handler, fields, anonymous)

        try:
            if self.stream: stream = srl.stream_render(request)
            else: stream = srl.render(request)

            if not isinstance(stream, HttpResponse):
                resp = HttpResponse(stream, mimetype=ct, status=status_code)
            else:
                resp = stream
            resp.streaming = self.stream
            return resp
        except HttpStatusCode, e:
            return e.response
コード例 #14
0
ファイル: resource.py プロジェクト: D3f0/django-admin-extras
    def ___call__(self, request, *args, **kwargs):
        """
        NB: Sends a `Vary` header so we don't cache requests
        that are different (OAuth stuff in `Authorization` header.)
        """
        # from ipdb import set_trace; set_trace()
        rm = request.method.upper()

        # Django's internal mechanism doesn't pick up
        # PUT request, so we trick it a little here.
        if rm == "PUT":
            coerce_put_post(request)

        if not self.authentication.is_authenticated(request):
            if (
                hasattr(self.handler, "anonymous")
                and callable(self.handler.anonymous)
                and rm in self.handler.anonymous.allowed_methods
            ):

                handler = self.handler.anonymous()
                anonymous = True
            else:
                return self.authentication.challenge()
        else:
            handler = self.handler
            anonymous = handler.is_anonymous

        # Translate nested datastructs into `request.data` here.
        if rm in ("POST", "PUT"):
            try:
                # from ipdb import set_trace; set_trace()
                translate_mime(request)
            except MimerDataException:
                pass
                # print "Error de Mime"
                # return rc.BAD_REQUEST

        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)

        meth = getattr(handler, self.callmap.get(rm), None)

        if not meth:
            raise Http404

        # Support emitter both through (?P<emitter_format>) and ?format=emitter.
        em_format = self.determine_emitter(request, *args, **kwargs)

        kwargs.pop("emitter_format", None)

        # Clean up the request object a bit, since we might
        # very well have `oauth_`-headers in there, and we
        # don't want to pass these along to the handler.
        request = self.cleanup_request(request)

        try:
            result = meth(request, *args, **kwargs)
        except FormValidationError, e:
            # TODO: Use rc.BAD_REQUEST here
            return HttpResponse("Bad Request: %s" % e.form.errors, status=400)