Ejemplo n.º 1
0
    def test_determine_format(self):
        serializer = Serializer()
        full_serializer = Serializer(formats=['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
        request = HttpRequest()
        
        # Default.
        self.assertEqual(determine_format(request, serializer), 'application/json')
        
        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Disabled by default.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Explicitly enabled.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, full_serializer), 'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')
        
        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')
        
        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')
        
        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
        
        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
Ejemplo n.º 2
0
    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                "list_endpoint": self._build_reverse_url(
                    "api_dispatch_list", kwargs={"api_name": api_name, "resource_name": name}
                ),
                "schema": self._build_reverse_url(
                    "api_get_schema", kwargs={"api_name": api_name, "resource_name": name}
                ),
            }

        desired_format = determine_format(request, self.serializer)

        options = {}

        if "text/javascript" in desired_format:
            callback = request.GET.get("callback", "callback")

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest("JSONP callback name is invalid.")

            options["callback"] = callback

        serialized = self.serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 3
0
 def determine_format(self, request):
     """return application/json as the default format """
     fmt = determine_format(request, self._meta.serializer,\
                            default_format=self._meta.default_format)
     if fmt == 'text/html' and 'format' not in request:
         fmt = 'application/json'
     return fmt
Ejemplo n.º 4
0
 def top_level(self, request, api_name=None):
     """
     A view that returns a serialized list of all resources registers
     to the ``Api``. Useful for discovery.
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     serialized = serializer.serialize(available_resources, desired_format)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 5
0
def top_level(request):
    available_resources = {}

    apitop = reverse('ietf.api.top_level')

    for name in sorted([ name for name, api in _api_list if len(api._registry) > 0 ]):
        available_resources[name] = {
            'list_endpoint': '%s/%s/' % (apitop, name),
        }

    serializer = Serializer()
    desired_format = determine_format(request, serializer)

    options = {}

    if 'text/javascript' in desired_format:
        callback = request.GET.get('callback', 'callback')

        if not is_valid_jsonp_callback_value(callback):
            raise BadRequest('JSONP callback name is invalid.')

        options['callback'] = callback

    serialized = serializer.serialize(available_resources, desired_format, options)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 6
0
    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        serializer = Serializer()

        if api_name is None:
            api_name = self.api_name

        available_resources = dict((name, {
            'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
            'schema': self._build_reverse_url("api_get_schema", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
        }) for name in self._registry.iterkeys())

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 7
0
def login(request, **kwargs):
    # self.method_check(request, allowed=['post'])
    # self.is_authenticated(request)
    # self.throttle_check(request)

    developer_key = request.GET.get('developer_key')
    username = request.GET.get('username')
    password = request.GET.get('password')

    if not developer_key or not username or not password:
        return HttpUnauthorized()

    try:
        dev_key = DeveloperApiKey.objects.get(key=developer_key, approved=True)
    except DeveloperApiKey.DoesNotExist:
        return HttpUnauthorized()

    user = authenticate(username=username, password=password)

    if user:
        try:
            key = UserApiKey.objects.get(user=user, developer_key=dev_key)
        except  UserApiKey.DoesNotExist:
            key = UserApiKey(user=user, developer_key=dev_key)
            key.save()

        # self.log_throttled_access(request)
        serializer = Serializer()
        desired_format = determine_format(request, serializer)
        serialized = serializer.serialize({'key' : key.key}, desired_format)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
    else:
        return HttpUnauthorized()
Ejemplo n.º 8
0
Archivo: utils.py Proyecto: bne/hortee
 def serialized(self, request, api_name=None, desired_format=None):
     """
     Nabbed from top_level of the parent class
     Would be nice if this was abstracted as it's good for auto discovery
     to be rendered as json on initial page load
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
         
     if desired_format is None:
         desired_format = determine_format(request, serializer)
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", 
             kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     return serializer.serialize(available_resources, desired_format)
Ejemplo n.º 9
0
 def top_level(self, request, api_name=None):
     """This is the same method in the Api model with the execption
     of the serializer used. This uses the SafeSerializer.
     """
     serializer = SafeSerializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     options = {}
     
     if 'text/javascript' in desired_format:
         callback = request.GET.get('callback', 'callback')
     
         if not is_valid_jsonp_callback_value(callback):
             raise BadRequest('JSONP callback name is invalid.')
     
         options['callback'] = callback
     
     serialized = serializer.serialize(available_resources, desired_format, options)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 10
0
def error_response(request, error_code=None, message=None, status_code=403, serializer_class=HTMLSerializer, **kwargs):
    context = {}
    if error_code:
        context['error_code'] = error_code

        if not message:
            message = ERRORS[error_code].format(**kwargs)
    if message:
        context['error_message'] = message

    context.update(kwargs)

    serializer = serializer_class()

    desired_format = determine_format(request, serializer)
    options = {}

    if 'text/javascript' in desired_format:
        callback = request.GET.get('callback', 'callback')

        if not is_valid_jsonp_callback_value(callback):
            raise BadRequest('JSONP callback name is invalid.')

        options['callback'] = callback

    serialized = serializer.serialize(context, desired_format, options)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format), status=status_code)
Ejemplo n.º 11
0
    def top_level(self, request, api_name=None):
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url('api_dispatch_list', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'schema': self._build_reverse_url('api_get_schema', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
            }

            if request.GET.get('include_schemas', False) is not False:
                available_resources[name]['schema_detailed'] = self._registry[name].build_schema()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')
            
            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 12
0
 def determine_format(self, request):
     """
     return application/json as the default format
     """
     fmt = determine_format(request, self._meta.serializer, default_format=self._meta.default_format)
     if fmt == "text/html" and "format" not in request:
         fmt = "application/json"
     return fmt
Ejemplo n.º 13
0
 def determine_format(self, request):
     """
     Used to determine the desired format.
     
     Largely relies on ``tastypie.utils.mime.determine_format`` but here
     as a point of extension.
     """
     return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)
Ejemplo n.º 14
0
    def determine_format(self, request):
        '''
            Overriding this to by pass text/html format when accessing ``API
            directly through browser.
        '''
        req_format = determine_format(request, self._meta.serializer,
                                      default_format=self._meta.default_format)
        if req_format == "text/html":
            req_format = self._meta.default_format

        return req_format
Ejemplo n.º 15
0
def is_key_valid(request, **kwargs):
    user_key = request.GET.get('user_key')
    try:
        user_key = UserApiKey.objects.get(key=user_key)
        key_valid = True
    except UserApiKey.DoesNotExist:
        key_valid = False
        # self.log_throttled_access(request)
    serializer = Serializer()
    desired_format = determine_format(request, serializer)
    serialized = serializer.serialize({'valid' : key_valid}, desired_format)
    return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 16
0
def view_response(request, response, code):
    from django.http import HttpResponse
    from tastypie.serializers import Serializer
    from tastypie.utils.mime import determine_format

    serdes = Serializer(formats=["json", "xml"])
    mimetype = determine_format(request, serdes)
    response = serdes.serialize(response, mimetype)
    del serdes

    http_response = HttpResponse(response, mimetype=mimetype)
    http_response.status_code = code
    return http_response
Ejemplo n.º 17
0
def sign_up(request):
    """
        Create a new user including profile and send email with activation link.
    """
    form = SignUpForm(request.POST)
    serializer = Serializer()
    format = determine_format(request, serializer,
        default_format='application/json')

    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']

        # Create new user (profile is automatically created)
        user = User.objects.create(username=username, first_name=first_name,
            last_name=last_name, email=email, is_active=False)
        user.set_password(password)
        user.save()

        auth_profile = user.get_profile()

        # Build the activation key
        salt = sha.new(str(random())).hexdigest()[:5]
        activation_key = sha.new(salt + user.username).hexdigest()
        key_expires = datetime.datetime.now(pytz.utc) + datetime.timedelta(2)

        # User is unactive until visiting activation link
        auth_profile.activation_key = activation_key
        auth_profile.key_expires = key_expires
        activation_link = 'http://127.0.0.1:8000/auth/v1/activate/' + activation_key  # TODO: replace with actual actication link (http://api.score-it.de/auth/v1/activate/)

        auth_profile.save()

        # TODO: Design better email
        subject = _('Welcome to ScoreIt!')
        message = _('To activate, please click the following link:\n' + activation_link)
        sender = _('*****@*****.**')
        recipients = [email]
        send_mail(subject, message, sender, recipients)

        user_resource = UserResource()
        bundle = user_resource.build_bundle(obj=user, request=request)
        user_resource.full_dehydrate(bundle)

        return HttpResponse(user_resource.serialize(None, bundle, 'application/json'))
    else:
        return HttpResponseBadRequest(serializer.serialize(form.errors, format, {}))
Ejemplo n.º 18
0
    def top_level(self, request, api_name=None):
        serializer = PrettyJSONSerializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        def render_resource(name, resource):
            dct = {
                'apidoc': self._build_reverse_url("api_get_doc", kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'relativePath': resource.get_relative_uri(),
                'schema': self._build_reverse_url("api_get_schema", kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'views': {}
            }

            for _, viewmeta in resource.viewregistry.get_all():
                view_name = viewmeta.name
                dct['views'][view_name] = viewmeta.get_template_uri(resource)

            if resource.children:
                dct['children'] = {}
                for child in resource.children:
                    n = child._meta.resource_name
                    dct['children'][n] = render_resource(n, child)

            return dct

        for name, resource in self._registry.items():
            if not resource.parent:
                available_resources[name] = render_resource(name, resource)

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 19
0
    def top_level(self, request, api_name=None):
        """This is the same method in the Api model with the execption
        of the serializer used. This uses the SafeSerializer.
        """
        serializer = SafeSerializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                'list_endpoint':
                self._build_reverse_url("api_dispatch_list",
                                        kwargs={
                                            'api_name': api_name,
                                            'resource_name': name,
                                        }),
                'schema':
                self._build_reverse_url("api_get_schema",
                                        kwargs={
                                            'api_name': api_name,
                                            'resource_name': name,
                                        }),
            }

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format,
                                          options)
        return HttpResponse(content=serialized,
                            content_type=build_content_type(desired_format))
Ejemplo n.º 20
0
    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        kwargs = {}
        if not self._accept_header_routing:
            kwargs['api_name'] = api_name

        for name in sorted(self._registry.keys()):
            kwargs['resource_name'] = name
            available_resources[name] = {
                'list_endpoint':
                self._build_reverse_url("api_dispatch_list", kwargs=kwargs),
                'schema':
                self._build_reverse_url("api_get_schema", kwargs=kwargs),
            }

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format,
                                          options)
        content_type = self._build_content_type(desired_format)
        return HttpResponse(content=serialized, content_type=content_type)
Ejemplo n.º 21
0
    def top_level(self, request, api_name=None, **kwargs):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        # TODO: Limit visibility of API to valid site IDs only.
        # TODO: Potentially, we could only give pieces of the API out based on site ID.

        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            kw_bru = {
                'api_name': api_name,
                'resource_name': name,
                }
            kw_bru.update(self._registry[name].api_additional_parameters())
            kw_bru.update(kwargs)
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs=kw_bru),
                'schema': self._build_reverse_url("api_get_schema", kwargs=kw_bru),
                }

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 22
0
    def top_level(self, request, api_name=None):
        """
        Overriding top_level method to serialize only resources
        that user has rights to use.
        """
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for resource_name in sorted(self._registry.keys()):
            available_resources[resource_name] = {
                'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                    'api_name': api_name,
                    'resource_name': resource_name,
                }),
                'schema': self._build_reverse_url("api_get_schema", kwargs={
                    'api_name': api_name,
                    'resource_name': resource_name,
                }),
            }

        if not available_resources:
            return HttpResponseForbidden()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
Ejemplo n.º 23
0
def is_unique(request):
    """
        Check if a username or email exists already
    """
    data = {}

    if 'user_name' in request.GET:
        username = request.GET['user_name']

        try:
            User.objects.get(username=username)
            unique = False
        except User.DoesNotExist:
            unique = True
        except User.MultipleObjectsReturned:
            unique = False

        data['user_name'] = unique

    if 'email' in request.GET:
        email = request.GET['email']

        try:
            User.objects.get(email=email)
            unique = False
        except User.DoesNotExist:
            unique = True
        except User.MultipleObjectsReturned:
            unique = False

        data['email'] = unique

    serializer = Serializer()

    format = determine_format(request, serializer, default_format='application/json')

    return HttpResponse(serializer.serialize(data, format, {}))
Ejemplo n.º 24
0
def is_unique(request):
    """
        Check if pass number already exists
    """
    data = {}

    if 'pass_number' in request.GET:
        pass_number = request.GET['pass_number']

        try:
            Person.objects.get(pass_number=pass_number)
            unique = False
        except Person.DoesNotExist:
            unique = True
        except Person.MultipleObjectsReturned:
            unique = False

        data['pass_number'] = unique

    serializer = Serializer()

    format = determine_format(request, serializer, default_format='application/json')

    return HttpResponse(serializer.serialize(data, format, {}))
Ejemplo n.º 25
0
    def test_determine_format(self):
        serializer = Serializer()
        request = HttpRequest()

        # Default.
        self.assertEqual(determine_format(request, serializer), "application/json")

        # Test forcing the ``format`` parameter.
        request.GET = {"format": "json"}
        self.assertEqual(determine_format(request, serializer), "application/json")

        request.GET = {"format": "jsonp"}
        self.assertEqual(determine_format(request, serializer), "text/javascript")

        request.GET = {"format": "xml"}
        self.assertEqual(determine_format(request, serializer), "application/xml")

        request.GET = {"format": "yaml"}
        self.assertEqual(determine_format(request, serializer), "text/yaml")

        request.GET = {"format": "foo"}
        self.assertEqual(determine_format(request, serializer), "application/json")

        # Test the ``Accept`` header.
        request.META = {"HTTP_ACCEPT": "application/json"}
        self.assertEqual(determine_format(request, serializer), "application/json")

        request.META = {"HTTP_ACCEPT": "text/javascript"}
        self.assertEqual(determine_format(request, serializer), "text/javascript")

        request.META = {"HTTP_ACCEPT": "application/xml"}
        self.assertEqual(determine_format(request, serializer), "application/xml")

        request.META = {"HTTP_ACCEPT": "text/yaml"}
        self.assertEqual(determine_format(request, serializer), "text/yaml")

        request.META = {"HTTP_ACCEPT": "text/html"}
        self.assertEqual(determine_format(request, serializer), "text/html")

        request.META = {"HTTP_ACCEPT": "application/json,application/xml;q=0.9,*/*;q=0.8"}
        self.assertEqual(determine_format(request, serializer), "application/json")

        request.META = {"HTTP_ACCEPT": "text/plain,application/xml,application/json;q=0.9,*/*;q=0.8"}
        self.assertEqual(determine_format(request, serializer), "application/xml")
Ejemplo n.º 26
0
    def process_response(self, request, response):
        if hasattr(request, 'user') and request.user.is_authenticated():
            credentials = request.user.pk
        else:
            credentials = -1
        serializer = Serializer()
        format = determine_format(request,
                                  serializer,
                                  default_format='application/json')
        # clean POST received from client
        if request.method in ['POST', 'PUT']:
            try:
                cleansed = serializer.deserialize(request.body, format=format)
            except ValueError:
                cleansed = request.POST.dict()
            except UnsupportedFormat:
                cleansed = 'UNSUPPORTED_FORMAT'
            except AttributeError:
                cleansed = 'UNSUPPORTED_STRING'
            except Exception as e:
                logger.warning(u"[RESPONSE] %(c)s: %(e)s", {
                    'c': e.__class__,
                    'e': e
                })
                cleansed = 'STRING'
            finally:
                if hasattr(cleansed, 'keys'):
                    cleansed.update(
                        dict((param, CLEANSED_SUBSTITUTE)
                             for param in SENSITIVE_PARAMS
                             if param in cleansed))
        else:
            cleansed = 'STRING'
        # clean response sent to client
        if response.content and settings.FULL_RESPONSE_LOGGING:
            try:
                content = response.content

            except AttributeError:
                content = 'UNSUPPORTED_STRING'
            except (UnsupportedFormat, ValueError):
                content = 'UNSUPPORTED_FORMAT'
        else:
            content = 'HIDDEN'
        # clean headers from client
        if settings.FULL_HEADER_LOGGING:
            cleansed_headers = getattr(request, 'META', {})
            cleansed_headers.update(
                dict((param, CLEANSED_SUBSTITUTE)
                     for param in SENSITIVE_HEADERS
                     if param in cleansed_headers))
        else:
            cleansed_headers = ''

        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0]
        else:
            ip = request.META['REMOTE_ADDR']

        logger.info(
            u"[ACCESS] %(h)s %(l)s user=%(u)s - %(t)s \"%(r)s\" status=%(s)s "
            u"%(b)s - \"%(f)s\" - \"%(a)s\" - data=%(i)s - headers=%(j)s -"
            u"content=%(o)s", {
                'h':
                ip,
                'l':
                '-',
                'u':
                credentials,
                't':
                datetime.datetime.now(),
                'r':
                '%s %s' % (request.method, request.get_full_path()),
                's':
                response.status_code,
                'b':
                request.META.get('CONTENT_LENGTH', ''),
                'f':
                request.META.get('HTTP_REFERER', ''),
                'a':
                request.META.get('HTTP_USER_AGENT', '').decode(
                    'utf-8', 'replace'),
                'i':
                cleansed,
                'o':
                content,
                'j':
                cleansed_headers
            })
        return response
Ejemplo n.º 27
0
    def top_level(self, request, api_name=None):
        """
        this is a copy/past of the method Api.top_level
        the original method locally use a Serializer object which didn't
        implement the `to_html` method
        this function does exactly the same except it can server html content
        """

        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            kwargs = {
                'api_name': api_name,
                'resource_name': name,
            }
            available_resources[name] = {
                'list_endpoint':
                self._build_reverse_url("api_dispatch_list", kwargs=kwargs),
                'schema':
                self._build_reverse_url("api_get_schema", kwargs=kwargs),
            }

        desired_format = determine_format(request, serializer)
        options = {}
        if 'text/html' in desired_format:
            serialized = textwrap.dedent("""
            <!DOCTYPE html>
            <html>
              <head>
                <style>
                  body {
                    font-family: Monaco,"DejaVu Sans Mono",
                                 "Courier New",monospace;
                  }
                  div {
                    margin: 5px;
                    padding: 5px;
                    border: 1px solid #444;
                    border-radius: 5px;
                    background-color: #eee;
                  }
                  h1 {
                    font-size: 1.4rem;
                  }
                  .command:before {
                    font-size: 1.4rem;
                  }
                </style>
              </head>
              <title>Api route</title>
              <body>
                <div>
                  <h1 class="command">Available route</h1>
                  <pre>%s</pre>
                </div>
              </body>
            </html>
            """) % json.dumps(available_resources, indent=4, sort_keys=True)
        else:
            if 'text/javascript' in desired_format:
                callback = request.GET.get('callback', 'callback')
                if not is_valid_jsonp_callback_value(callback):
                    raise BadRequest('JSONP callback name is invalid.')
                options['callback'] = callback
            serialized = serializer.serialize(available_resources,
                                              desired_format, options)
        return HttpResponse(content=serialized,
                            content_type=build_content_type(desired_format))
Ejemplo n.º 28
0
    def test_determine_format(self):
        serializer = Serializer()
        full_serializer = Serializer(formats=['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
        request = HttpRequest()

        # Default.
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Disabled by default.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Explicitly enabled.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, full_serializer), 'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')

        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Again, disabled by default.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Again, explicitly enabled.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, full_serializer), 'text/javascript')

        request.META = {'HTTP_ACCEPT': 'application/xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.META = {'HTTP_ACCEPT': 'text/yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.META = {'HTTP_ACCEPT': 'application/x-plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')

        request.META = {'HTTP_ACCEPT': 'text/html'}
        self.assertEqual(determine_format(request, serializer), 'text/html')

        request.META = {'HTTP_ACCEPT': '*/*'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.META = {'HTTP_ACCEPT': 'application/json; charset=UTF-8'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript,application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'bogon'}
        self.assertRaises(BadRequest, determine_format, request, serializer)
Ejemplo n.º 29
0
    def batch(self, request, api_name=None):
        """
        Make batch requests to the api.
        """
        # assert False, request
        if not request.method.lower() == 'post':
            raise Http404
        if api_name is None:
            api_name = self.api_name


        desired_format = determine_format(request, self.serializer)

        try:
            batch_requests = self.serializer.deserialize(
                request.body, desired_format)[:BATCH_API_MAX_REQUESTS]
        except ValueError:
            raise BadRequest('Bad data.')
        if not isinstance(batch_requests, list):
            raise BadRequest('Bad structure.')
        responses = []
        if not request.session.exists(request.session.session_key):
            request.session.create()
        # assert False, request.session.session_key
        self.client.cookies[settings.SESSION_COOKIE_NAME] = \
            request.session.session_key
        for req in batch_requests:
            path = req.get('path')
            params = {}
            params.update(req.get('params', {}))
            response_obj = {
                'path': urllib.quote(path),
                'params': params,
            }
            valid_path = re.search(self.prefix, path)
            if valid_path:
                try:
                    setattr(self, '_client', Client(**request.META))
                    response = self.client.get(req['path'], params)
                    # assert False, dir(response)
                    response_obj['status'] = response.status_code
                    response_obj['body'] = response.content
                    response_obj['headers'] = response._headers
                    response_obj['cookies'] = response.cookies
                except:
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    response_obj['error'] = {
                        'exc_type': exc_type,
                        'exc_value': exc_value
                    }
                    if settings.DEBUG:
                        response_obj['exc_traceback'] = traceback.format_exc(
                            exc_traceback)
            else:
                # response_obj['status'] = 404
                response_obj['error'] = 'Unknown resource uri.',
            responses.append(response_obj)


        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = self.serializer.serialize(
            responses, desired_format, options)
        return HttpResponse(
            content=serialized, content_type=build_content_type(
                desired_format))
Ejemplo n.º 30
0
    def test_determine_format(self):
        serializer = Serializer()
        request = HttpRequest()

        # Default.
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer),
                         'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer),
                         'application/x-plist')

        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer),
                         'text/javascript')

        request.META = {'HTTP_ACCEPT': 'application/xml'}
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.META = {'HTTP_ACCEPT': 'text/yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.META = {'HTTP_ACCEPT': 'application/x-plist'}
        self.assertEqual(determine_format(request, serializer),
                         'application/x-plist')

        request.META = {'HTTP_ACCEPT': 'text/html'}
        self.assertEqual(determine_format(request, serializer), 'text/html')

        request.META = {'HTTP_ACCEPT': '*/*'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {
            'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'
        }
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {
            'HTTP_ACCEPT':
            'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'
        }
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.META = {'HTTP_ACCEPT': 'application/json; charset=UTF-8'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript,application/json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')
Ejemplo n.º 31
0
 def determine_format(self, request):
     return determine_format(request, self.serializer, default_format=self.default_format)
Ejemplo n.º 32
0
    def test_determine_format(self):
        serializer = Serializer()
        full_serializer = Serializer(
            formats=['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
        request = HttpRequest()

        # Default.
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Disabled by default.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Explicitly enabled.
        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, full_serializer),
                         'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer),
                         'application/x-plist')

        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Again, disabled by default.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        # Again, explicitly enabled.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, full_serializer),
                         'text/javascript')

        request.META = {'HTTP_ACCEPT': 'application/xml'}
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.META = {'HTTP_ACCEPT': 'text/yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.META = {'HTTP_ACCEPT': 'application/x-plist'}
        self.assertEqual(determine_format(request, serializer),
                         'application/x-plist')

        request.META = {'HTTP_ACCEPT': 'text/html'}
        self.assertEqual(determine_format(request, serializer), 'text/html')

        request.META = {'HTTP_ACCEPT': '*/*'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {
            'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'
        }
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {
            'HTTP_ACCEPT':
            'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'
        }
        self.assertEqual(determine_format(request, serializer),
                         'application/xml')

        request.META = {'HTTP_ACCEPT': 'application/json; charset=UTF-8'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript,application/json'}
        self.assertEqual(determine_format(request, serializer),
                         'application/json')

        request.META = {'HTTP_ACCEPT': 'bogon'}
        self.assertRaises(BadRequest, determine_format, request, serializer)
Ejemplo n.º 33
0
    def test_determine_format(self):
        serializer = Serializer()
        request = HttpRequest()

        # Default.
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Test forcing the ``format`` parameter.
        request.GET = {'format': 'json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.GET = {'format': 'jsonp'}
        self.assertEqual(determine_format(request, serializer), 'text/javascript')

        request.GET = {'format': 'xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.GET = {'format': 'yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')

        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer), 'text/javascript')

        request.META = {'HTTP_ACCEPT': 'application/xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.META = {'HTTP_ACCEPT': 'text/yaml'}
        self.assertEqual(determine_format(request, serializer), 'text/yaml')

        request.META = {'HTTP_ACCEPT': 'application/x-plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')

        request.META = {'HTTP_ACCEPT': 'text/html'}
        self.assertEqual(determine_format(request, serializer), 'text/html')

        request.META = {'HTTP_ACCEPT': '*/*'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')

        request.META = {'HTTP_ACCEPT': 'application/json; charset=UTF-8'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        request.META = {'HTTP_ACCEPT': 'text/javascript,application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
Ejemplo n.º 34
0
        self.assertEqual(determine_format(request, serializer), 'text/yaml')
        
        request.GET = {'format': 'plist'}
        self.assertEqual(determine_format(request, serializer), 'application/x-plist')
        
        request.GET = {'format': 'foo'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
        
        # Test the ``Accept`` header.
        request.META = {'HTTP_ACCEPT': 'application/json'}
        self.assertEqual(determine_format(request, serializer), 'application/json')
<<<<<<< HEAD

        # Again, disabled by default.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer), 'application/json')

        # Again, explicitly enabled.
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, full_serializer), 'text/javascript')

=======
        
        request.META = {'HTTP_ACCEPT': 'text/javascript'}
        self.assertEqual(determine_format(request, serializer), 'text/javascript')
        
>>>>>>> parent of 609f2e2... Fixed a bug where JSON/JSONP was returning an invalid ``charset`` within the MIME type. Thanks to dstufft for the report!
        request.META = {'HTTP_ACCEPT': 'application/xml'}
        self.assertEqual(determine_format(request, serializer), 'application/xml')
        
        request.META = {'HTTP_ACCEPT': 'text/yaml'}
Ejemplo n.º 35
0
    def process_response(self, request, response):
        if hasattr(request, 'user') and request.user.is_authenticated():
            credentials = request.user.pk
        else:
            credentials = -1
        serializer = Serializer()
        format = determine_format(
            request, serializer, default_format='application/json')
        # clean POST received from client
        if request.method in ['POST', 'PUT']:
            try:
                cleansed = serializer.deserialize(
                    request.body,
                    format=format)
            except ValueError:
                cleansed = request.POST.dict()
            except UnsupportedFormat:
                cleansed = 'UNSUPPORTED_FORMAT'
            except AttributeError:
                cleansed = 'UNSUPPORTED_STRING'
            except Exception as e:
                logger.warning(
                    u"[RESPONSE] %(c)s: %(e)s",
                    {'c': e.__class__, 'e': e})
                cleansed = 'STRING'
            finally:
                if hasattr(cleansed, 'keys'):
                    cleansed.update(
                        dict(
                            (param, CLEANSED_SUBSTITUTE)
                            for param in SENSITIVE_PARAMS
                            if param in cleansed))
        else:
            cleansed = 'STRING'
        # clean response sent to client
        if response.content and settings.FULL_RESPONSE_LOGGING:
            try:
                content = response.content
                    
            except AttributeError:
                content = 'UNSUPPORTED_STRING'
            except (UnsupportedFormat, ValueError):
                content = 'UNSUPPORTED_FORMAT'
        else:
            content = 'HIDDEN'
        # clean headers from client
        if settings.FULL_HEADER_LOGGING:
                cleansed_headers = getattr(request, 'META', {})
                cleansed_headers.update(
                    dict(
                        (param, CLEANSED_SUBSTITUTE)
                        for param in SENSITIVE_HEADERS
                        if param in cleansed_headers))
        else:
            cleansed_headers = ''

        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0]
        else:
            ip = request.META['REMOTE_ADDR']

        logger.info(
            u"[ACCESS] %(h)s %(l)s user=%(u)s - %(t)s \"%(r)s\" status=%(s)s "
            u"%(b)s - \"%(f)s\" - \"%(a)s\" - data=%(i)s - headers=%(j)s -"
            u"content=%(o)s",
            {
                'h': ip,
                'l': '-',
                'u': credentials,
                't': datetime.datetime.now(),
                'r': '%s %s' % (request.method, request.get_full_path()),
                's': response.status_code,
                'b': request.META.get('CONTENT_LENGTH', ''),
                'f': request.META.get('HTTP_REFERER', ''),
                'a': request.META.get(
                    'HTTP_USER_AGENT', '').decode('utf-8', 'replace'),
                'i': cleansed,
                'o': content,
                'j': cleansed_headers}
        )
        return response
Ejemplo n.º 36
0
Archivo: urls.py Proyecto: Gandi/baobab
    def top_level(self, request, api_name=None):
        """
        this is a copy/past of the method Api.top_level
        the original method locally use a Serializer object which didn't
        implement the `to_html` method
        this function does exactly the same except it can server html content
        """

        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            kwargs = {
                'api_name': api_name,
                'resource_name': name,
            }
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url("api_dispatch_list",
                                                         kwargs=kwargs),
                'schema': self._build_reverse_url("api_get_schema",
                                                  kwargs=kwargs),
            }

        desired_format = determine_format(request, serializer)
        options = {}
        if 'text/html' in desired_format:
            serialized = textwrap.dedent("""
            <!DOCTYPE html>
            <html>
              <head>
                <style>
                  body {
                    font-family: Monaco,"DejaVu Sans Mono",
                                 "Courier New",monospace;
                  }
                  div {
                    margin: 5px;
                    padding: 5px;
                    border: 1px solid #444;
                    border-radius: 5px;
                    background-color: #eee;
                  }
                  h1 {
                    font-size: 1.4rem;
                  }
                  .command:before {
                    font-size: 1.4rem;
                  }
                </style>
              </head>
              <title>Api route</title>
              <body>
                <div>
                  <h1 class="command">Available route</h1>
                  <pre>%s</pre>
                </div>
              </body>
            </html>
            """) % json.dumps(available_resources, indent=4, sort_keys=True)
        else:
            if 'text/javascript' in desired_format:
                callback = request.GET.get('callback', 'callback')
                if not is_valid_jsonp_callback_value(callback):
                    raise BadRequest('JSONP callback name is invalid.')
                options['callback'] = callback
            serialized = serializer.serialize(available_resources,
                                              desired_format, options)
        return HttpResponse(content=serialized,
                            content_type=build_content_type(desired_format))