Ejemplo n.º 1
0
    def process_response(self, request, response):
        language = translation.get_language()
        if self.use_redirects:
            kwargs = {}
            if django_root_version == 16:
                kwargs['supported'] = self._supported_languages
            language_from_path = translation.get_language_from_path(
                request.path_info, **kwargs)
            if (response.status_code == 404 and not language_from_path
                    and self.is_language_prefix_patterns_used()
                    and language != self.default_lang):
                urlconf = getattr(request, 'urlconf', None)
                language_path = '/%s%s' % (language, request.path_info)
                path_valid = is_valid_path(language_path, urlconf)
                if (not path_valid and settings.APPEND_SLASH
                        and not language_path.endswith('/')):
                    path_valid = is_valid_path("%s/" % language_path, urlconf)

                if path_valid:
                    language_url = "%s://%s/%s%s" % (
                        'https' if request.is_secure() else 'http',
                        request.get_host(), language, request.get_full_path())
                    return HttpResponseRedirect(language_url)

            if not (self.is_language_prefix_patterns_used()
                    and language_from_path):
                patch_vary_headers(response, ('Accept-Language',))
            if django_root_version < 16:
                translation.deactivate()
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 2
0
    def process_response(self, request, response):
        # First set the default language, this will be used if there is none
        # in the path
        default_language = getattr(request, 'default_language', '')
        if default_language:
            translation.activate(default_language)

        language = translation.get_language()
        if (response.status_code == 404 and
                not translation.get_language_from_path(request.path_info) and
                self.is_language_prefix_patterns_used(request)):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            if settings.APPEND_SLASH and not language_path.endswith('/'):
                language_path += '/'

            if is_valid_path(language_path, urlconf):
                language_url = "%s://%s/%s%s" % (
                    request.is_secure() and 'https' or 'http',
                    request.get_host(), language, request.get_full_path())
                return HttpResponseRedirect(language_url)
        translation.deactivate()

        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 3
0
def buildfeed(request, feedclass, tag=None, user=None):
    """ View that handles the feeds.
    """

    response, site, cachekey, sfeeds_obj, sfeeds_ids = initview(request)
    if response:
        return response

    object_list = fjlib.get_paginator(site, sfeeds_ids, page=0, tag=tag, \
      user=user)[1]

    feed = feedclass(\
        title=site.title,
        link=site.url,
        description=site.description,
        feed_url='%s/%s' % (site.url, '/feed/rss/'))
    for post in object_list:
        feed.add_item( \
          title = '%s: %s' % (post.feed.name, post.title), \
          link = post.link, \
          description = post.content, \
          author_email = post.author_email, \
          author_name = post.author, \
          pubdate = post.date_modified, \
          unique_id = post.link, \
          categories = [tag.name for tag in post.tags.all()])
    response = HttpResponse(mimetype=feed.mime_type)

    # per host caching
    patch_vary_headers(response, ['Host'])

    feed.write(response, 'utf-8')
    if site.use_internal_cache:
        fjcache.cache_set(site, cachekey, response)
    return response
Ejemplo n.º 4
0
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie.
     """
     try:
         accessed = request.session.accessed
         modified = request.session.modified
     except AttributeError:
         pass
     else:
         if accessed:
             patch_vary_headers(response, ('Cookie',))
         if modified or settings.SESSION_SAVE_EVERY_REQUEST:
             if request.session.get_expire_at_browser_close():
                 max_age = None
                 expires = None
             else:
                 max_age = request.session.get_expiry_age()
                 expires_time = time.time() + max_age
                 expires = cookie_date(expires_time)
             # Save the session data and refresh the client cookie.
             # Skip session save for 500 responses, refs #3881.
             if response.status_code != 500:
                 request.session.save()
                 paths = getattr(settings, 'EPO_SESSION_ACCESS_PATHS', [settings.SESSION_COOKIE_PATH])
                 for p in paths:
                     response.set_cookie(cookie_name_gen(p) if p != settings.SESSION_COOKIE_PATH else p,
                                         request.session.session_key, max_age=max_age,
                                         expires=expires, domain=get_domain(),
                                         path=p,
                                         secure=settings.SESSION_COOKIE_SECURE or None,
                                         httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Ejemplo n.º 5
0
def fetch_render_snippets(request, **kwargs):
    """Fetch snippets for the client and render them immediately."""
    client = Client(**kwargs)
    matching_snippets = (Snippet.cached_objects
                         .filter(disabled=False)
                         .match_client(client)
                         .order_by('priority')
                         .select_related('template')
                         .filter_by_available())

    current_firefox_version = (
        version_list(product_details.firefox_history_major_releases)[0].split('.', 1)[0])

    metrics_url = settings.METRICS_URL
    if ((settings.ALTERNATE_METRICS_URL and
         client.channel in settings.ALTERNATE_METRICS_CHANNELS)):
        metrics_url = settings.ALTERNATE_METRICS_URL

    response = render(request, 'base/fetch_snippets.jinja', {
        'snippet_ids': [snippet.id for snippet in matching_snippets],
        'snippets_json': json.dumps([s.to_dict() for s in matching_snippets]),
        'client': client,
        'locale': client.locale,
        'current_firefox_version': current_firefox_version,
        'metrics_url': metrics_url,
    })

    # ETag will be a hash of the response content.
    response['ETag'] = hashlib.sha256(response.content).hexdigest()
    patch_vary_headers(response, ['If-None-Match'])

    return response
Ejemplo n.º 6
0
Archivo: gzip.py Proyecto: lapbay/milan
	def process_response(self, request, response):
		# It's not worth compressing non-OK or really short responses.
		if response.status_code != 200 or len(response.content) < 200:
			return response

		patch_vary_headers(response, ('Accept-Encoding',))

		# Avoid gzipping if we've already got a content-encoding.
		if response.has_header('Content-Encoding'):
			return response

		# MSIE have issues with gzipped respones of various content types.
		if "msie" in request.META.get('HTTP_USER_AGENT', '').lower():
			ctype = response.get('Content-Type', '').lower()
			if not ctype.startswith("text/") or "javascript" in ctype:
				return response

		ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
		if not re_accepts_gzip.search(ae):
			return response

		response.content = compress_string(response.content)
		response['Content-Encoding'] = 'gzip'
		response['Content-Length'] = str(len(response.content))
		return response
Ejemplo n.º 7
0
    def finalize_response(self, request, response, *args, **kwargs):
        """
        Returns the final response object.
        """
        # Make the error obvious if a proper response is not returned
        assert isinstance(response, HttpResponseBase), (
            'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
            'to be returned from the view, but received a `%s`'
            % type(response)
        )

        if isinstance(response, Response):
            if not getattr(request, 'accepted_renderer', None):
                neg = self.perform_content_negotiation(request, force=True)
                request.accepted_renderer, request.accepted_media_type = neg

            response.accepted_renderer = request.accepted_renderer
            response.accepted_media_type = request.accepted_media_type
            response.renderer_context = self.get_renderer_context()

        # Add new vary headers to the response instead of overwriting.
        vary_headers = self.headers.pop('Vary', None)
        if vary_headers is not None:
            patch_vary_headers(response, cc_delim_re.split(vary_headers))

        for key, value in self.headers.items():
            response[key] = value

        return response
Ejemplo n.º 8
0
    def process_response(self, request, response):
        language = translation.get_language()
        if (response.status_code == 404 and
                not translation.get_language_from_path(request.path_info)
                    and self.is_language_prefix_patterns_used()):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                path = request.get_full_path()
                script_mount = request.META.get("SCRIPT_NAME", "")
                
                if path.startswith(script_mount):
                    path = path.replace(script_mount, ("%s/%s" % (script_mount, language)), 1)
                
                language_url = "%s://%s%s" % (
                    request.is_secure() and 'https' or 'http',
                    request.get_host(), path)
                return HttpResponseRedirect(language_url)
        translation.deactivate()

        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 9
0
    def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(
                request.path_info, supported=self._supported_languages
        )
        if (response.status_code == 404 and not language_from_path
                and self.is_language_prefix_patterns_used()):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                language_url = "%s://%s/%s%s" % (
                    request.scheme, request.get_host(), language,
                    request.get_full_path())
                return self.response_redirect_class(language_url)

        # Store language back into session if it is not present
        if hasattr(request, 'session'):
            request.session.setdefault('django_language', language)

        if not (self.is_language_prefix_patterns_used()
                and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
    def __call__(self, request):
        # Process the request
        domain = request.get_host().split(':')[0]
        self.site_aliases = getattr(settings, "SITE_ALIASES", {})

        query = Q(domain=domain)
        if domain in self.site_aliases:
            query |= Q(id=settings.SITE_ALIASES[domain])

        try:
            site = Site.objects.get(query)
        except Site.MultipleObjectsReturned:
            log.error('Multiple Sites found for query %r', query)
            if domain in self.site_aliases:
                site = Site.objects.get(id=settings.SITE_ALIASES[domain])
            else:
                site = Site.objects.get(domain=domain)
        except Site.DoesNotExist:
            site_id = getattr(settings, 'SITE_ID', 1)
            site, create = Site.objects.get_or_create(id=site_id, defaults={'domain': domain})
            create = "Creating" if create else "Using existing"
            log.error("Request on domain %s (%s) has no matching Site object. %s to %s",
                      "{}".format(domain), "{}".format(query), create, "{!r}".format(site))

        SITE_ID.value = site.id

        # Perform request
        response = self.get_response(request)

        # Process the response

        if getattr(request, "urlconf", None):
            patch_vary_headers(response, ('Host',))

        return response
Ejemplo n.º 11
0
    def process_response(self, request, response):
        if getattr(response, 'csrf_processing_done', False):
            return response

        # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was
        # never called, probaby because a request middleware returned a response
        # (for example, contrib.auth redirecting to a login page).
        if request.META.get("CSRF_COOKIE") is None:
            return response

        if not request.META.get("CSRF_COOKIE_USED", False):
            return response

        # Set the CSRF cookie even if it's already set, so we renew
        # the expiry timer.
        response.set_cookie(settings.CSRF_COOKIE_NAME,
                            request.META["CSRF_COOKIE"],
                            max_age = 60 * 60 * 24 * 7 * 52,
                            domain=settings.CSRF_COOKIE_DOMAIN,
                            path=settings.CSRF_COOKIE_PATH,
                            secure=settings.CSRF_COOKIE_SECURE,
                            httponly=settings.CSRF_COOKIE_HTTPONLY
                            )
        # Content varies with the CSRF cookie, so set the Vary header.
        patch_vary_headers(response, ('Cookie',))
        response.csrf_processing_done = True
        return response
Ejemplo n.º 12
0
    def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(request.path_info)
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)

        if response.status_code == 404 and not language_from_path and i18n_patterns_used:
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            path_needs_slash = (
                not path_valid and (
                    settings.APPEND_SLASH and not language_path.endswith('/')
                    and is_valid_path('%s/' % language_path, urlconf)
                )
            )

            if path_valid or path_needs_slash:
                script_prefix = get_script_prefix()
                # Insert language after the script prefix and before the
                # rest of the URL
                language_url = request.get_full_path(force_append_slash=path_needs_slash).replace(
                    script_prefix,
                    '%s%s/' % (script_prefix, language),
                    1
                )
                return self.response_redirect_class(language_url)

        if not (i18n_patterns_used and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 13
0
def blogroll(request, btype):
    """ View that handles the generation of blogrolls.
    """

    response, site, cachekey, sfeeds_obj, sfeeds_ids = initview(request)
    if response:
        return response

    # for some reason this isn't working:
    #
    #response = render_to_response('feedjack/%s.xml' % btype, \
    #  fjlib.get_extra_content(site, sfeeds_ids))
    #response.mimetype = 'text/xml; charset=utf-8'
    #
    # so we must use this:

    template = loader.get_template('feedjack/%s.xml' % btype)
    ctx = {}
    fjlib.get_extra_content(site, sfeeds_ids, ctx)
    ctx = Context(ctx)
    response = HttpResponse(template.render(ctx) , \
      mimetype='text/xml; charset=utf-8')


    patch_vary_headers(response, ['Host'])
    fjcache.cache_set(site, cachekey, response)
    return response
 def process_response(self, request, response):
     # If request.session was modified, or if response.session was set, save
     # those changes and set a session cookie.
     patch_vary_headers(response, ('Cookie',))
     try:
         modified = request.session.modified
     except AttributeError:
         pass
     else:
         if modified or settings.SESSION_SAVE_EVERY_REQUEST:
             session_key = request.session.session_key or Session.objects.get_new_session_key()
             
             if not request.session.get(settings.PERSISTENT_SESSION_KEY, False):
                 # session will expire when the user closes the browser
                 max_age = None
                 expires = None
             else:
                 max_age = settings.SESSION_COOKIE_AGE
                 expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
             
             new_session = Session.objects.save(session_key, 
                                                request.session._session,
                                                datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
             response.set_cookie(settings.SESSION_COOKIE_NAME, session_key,
                                 max_age = max_age, expires = expires, 
                                 domain = settings.SESSION_COOKIE_DOMAIN,
                                 secure = settings.SESSION_COOKIE_SECURE or None)
     return response
Ejemplo n.º 15
0
    def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(request.path_info)
        if (response.status_code == 404 and not language_from_path
                and self.is_language_prefix_patterns_used()):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                script_prefix = get_script_prefix()
                language_url = "%s://%s%s" % (
                    request.scheme,
                    request.get_host(),
                    # insert language after the script prefix and before the
                    # rest of the URL
                    request.get_full_path().replace(
                        script_prefix,
                        '%s%s/' % (script_prefix, language),
                        1
                    )
                )
                return self.response_redirect_class(language_url)

        if not (self.is_language_prefix_patterns_used()
                and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 16
0
def process_response(request, response):
    """
    If request.session was modified, or if the configuration is to save the
    session every time, save the changes and set a session cookie.
    """
    try:
        accessed = request.session.accessed
        modified = request.session.modified
    except AttributeError:
        pass
    else:
        if accessed:
            patch_vary_headers(response, ("Cookie",))
        if modified or settings.SESSION_SAVE_EVERY_REQUEST:
            if request.session.get_expire_at_browser_close():
                max_age = None
                expires = None
            else:
                max_age = request.session.get_expiry_age()
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
            request.session.save()
            response.set_cookie(
                settings.SESSION_COOKIE_NAME,
                request.session.session_key,
                max_age=max_age,
                expires=expires,
                domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=settings.SESSION_COOKIE_SECURE or None,
                httponly=settings.SESSION_COOKIE_HTTPONLY or None,
            )
    return response
Ejemplo n.º 17
0
    def process_response(self, request, response):
        html_types = ('text/html', 'application/xhtml+xml')
        content_type = response.get('Content-Type', '').split(';')[0]
        content_encoding = response.get('Content-Encoding', '')
        if any((getattr(response, 'streaming', False),
                'gzip' in content_encoding,
                content_type not in html_types)):
            return response

        if settings.RESPONSIVE_COOKIE_NAME not in request.COOKIES \
                or getattr(request, 'INVALID_RESPONSIVE_COOKIE', False):
            expires = datetime.datetime.utcnow() + \
                datetime.timedelta(days=settings.RESPONSIVE_COOKIE_AGE)
            snippet = render_to_string('responsive/snippet.html', {
                'cookie_name': settings.RESPONSIVE_COOKIE_NAME,
                'cookie_age': 60 * 60 * 24 * settings.RESPONSIVE_COOKIE_AGE,  # convert to secs
                'cookie_expires': expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
            })
            pattern = re.compile(b'<head>', re.IGNORECASE)
            response.content = pattern.sub(b'<head>' + smart_bytes(snippet), response.content)

            if response.get('Content-Length', None):
                response['Content-Length'] = len(response.content)

        patch_vary_headers(response, ('Cookie', ))
        return response
Ejemplo n.º 18
0
    def process_response(self, request, response):
        for authenticator in self.authenticators:
            authenticator.processResponse(request, response)

        # now save the multi site session
        # If request.ms_session was modified, or if response.session was set, save
        # those changes and set a session cookie.
        try:
            accessed = request.ms_session.accessed
            modified = request.ms_session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.ms_session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.ms_session.get_expiry_age()
                    expires_time = time.time() + max_age
                    # expires = cookie_date(expires_time)
                    expires = expires_time
                # Save the session data and refresh the client cookie.
                request.ms_session.save()
                response.set_cookie(MS_SESSION_COOKIE_NAME,
                        request.ms_session.session_key, max_age=max_age,
                        expires=expires, domain=MS_SESSION_COOKIE_DOMAIN,
                        path=MS_SESSION_COOKIE_PATH,
                        secure=MS_SESSION_COOKIE_SECURE or None)
        return response
Ejemplo n.º 19
0
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if True or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                request.session.save()

                #saving the user id in the cookie
                #user_info = "{'session_id':" + request.session.session_key +"/"+"anonymous_id:" + request.anonymous_id
                user_info = unicode({'session_id': request.session.session_key, 'anonymous_id': request.anonymous_id})

                user_info = quote(user_info)

                response.set_cookie(settings.SESSION_COOKIE_NAME,
                        user_info, max_age=max_age,
                        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                        path=settings.SESSION_COOKIE_PATH,
                        secure=settings.SESSION_COOKIE_SECURE or None)
        return response
Ejemplo n.º 20
0
    def process_response(self, request, response):
        # It's not worth attempting to compress really short responses.
        if not getattr(response, 'streaming', None) and len(response.content) < 200:
            return response

        # Avoid gzipping if we've already got a content-encoding.
        if response.has_header('Content-Encoding'):
            return response

        patch_vary_headers(response, ('Accept-Encoding',))

        ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
        if not re_accepts_gzip.search(ae):
            return response

        if getattr(response, 'streaming', None):
            # Delete the `Content-Length` header for streaming content, because
            # we won't know the compressed size until we stream it.
            response.streaming_content = compress_sequence(response.streaming_content)
            del response['Content-Length']
        else:
            # Return the compressed content only if it's actually shorter.
            compressed_content = compress_string(response.content)
            if len(compressed_content) >= len(response.content):
                return response
            response.content = compressed_content
            response['Content-Length'] = str(len(response.content))

        if response.has_header('ETag'):
            response['ETag'] = re.sub('"$', ';gzip"', response['ETag'])
        response['Content-Encoding'] = 'gzip'

        return response
Ejemplo n.º 21
0
    def serialize_response(self, response, status=200):
        """
        Serializes the response into an appropriate format for the wire such as
        JSON. ``HttpResponse`` instances are returned directly.
        """
        if isinstance(response, HttpResponse):
            return response

        formats = [
            ('application/json', {
                'handler': lambda response, output_format, config: (
                    HttpResponse(json.dumps(response, cls=DjangoJSONEncoder),
                        mimetype='application/json', status=status)),
                }),
            #('text/html', {
                #'handler': self.serialize_response_html,
                #}),
            ]

        # Thanks!
        # https://github.com/toastdriven/django-tastypie/blob/master/tastypie/utils/mime.py
        try:
            output_format = mimeparse.best_match(
                reversed([format for format, config in formats]),
                self.request.META.get('HTTP_ACCEPT'))
        except IndexError:
            output_format = 'application/json'

        config = dict(formats)[output_format]
        response = config['handler'](response, output_format, config)
        patch_vary_headers(response, ('Accept',))
        return response
Ejemplo n.º 22
0
 def _set_token(self, request, response):
     if request.user and request.user.is_authenticated():
         access_token = request.META.get('ACCESS_TOKEN', None)
         if access_token is None:
             Application = get_application_model()
             geoserver_app = Application.objects.get(name="GeoServer")
             token = generate_token()
             ttl = datetime.datetime.now() + datetime.timedelta(days=3)
             AccessToken.objects.get_or_create(user=request.user,
                                               application=geoserver_app,
                                               expires=ttl,
                                               token=token)
             access_token = token
         response.set_cookie(
             settings.ACCESS_TOKEN_NAME,
             access_token,
             max_age=settings.SESSION_COOKIE_AGE,
             domain=settings.SESSION_COOKIE_DOMAIN,
             path=settings.SESSION_COOKIE_PATH,
             secure=settings.SESSION_COOKIE_SECURE or None,
             httponly=settings.SESSION_COOKIE_HTTPONLY or None,)
         patch_vary_headers(response, ('Cookie',))
     else:
         response.delete_cookie(settings.ACCESS_TOKEN_NAME,
                                domain=settings.SESSION_COOKIE_DOMAIN)
Ejemplo n.º 23
0
    def process_response(self, request, response):
        """
        Override the original method to redirect permanently and facilitate 
        the :func.`translations.urls.translation_patterns` URL redirection
        logic.
        """
        language = translation.get_language()
        default = get_default_language()
        
        #redirect to the original default language URL
        #if language prefix is used
        if (response.status_code == 404 and
            self.is_language_prefix_patterns_used() and default == language and 
            request.path_info.startswith('/%s/' % default)):
            
            urlconf = getattr(request, 'urlconf', None)
            language_path = re.sub(r'^/%s/' % default, '/', request.path_info)
            if settings.APPEND_SLASH and not language_path.endswith('/'):
                language_path = language_path + '/'

            if is_valid_path(language_path, urlconf):
                #we use a permanent redirect here.
                #when changing the default language we need to let the world know
                #that our links have permanently changed and transfer our seo juice 
                #to the new url
                #http://blog.yawd.eu/2012/impact-django-page-redirects-seo/
                return  HttpResponsePermanentRedirect("%s://%s/%s" % (
                    request.is_secure() and 'https' or 'http',
                    request.get_host(), re.sub(r'^/%s/' % default, '', request.get_full_path())))
        
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 24
0
 def process_response(self, request, response):
     # We want to change the cookie, but didn't have the response in
     # process request.
     if hasattr(request, 'LANG_COOKIE'):
         response.set_cookie('lang', request.LANG_COOKIE)
     patch_vary_headers(response, ['Accept-Language', 'Cookie'])
     return response
Ejemplo n.º 25
0
    def process_response(self, request, response):
        if getattr(response, 'csrf_exempt', False):
            return response

        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            csrf_token = get_token(request)
            # If csrf_token is None, we have no token for this request, which probably
            # means that this is a response from a request middleware.
            if csrf_token is None:
                return response

            # ensure we don't add the 'id' attribute twice (HTML validity)
            idattributes = itertools.chain(("id='csrfmiddlewaretoken'",),
                                           itertools.repeat(''))
            def add_csrf_field(match):
                """Returns the matched <form> tag plus the added <input> element"""
                return mark_safe(match.group() + "<div style='display:none;'>" + \
                "<input type='hidden' " + idattributes.next() + \
                " name='csrfmiddlewaretoken' value='" + csrf_token + \
                "' /></div>")

            # Modify any POST forms
            response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content)
            if n > 0:
                # Content varies with the CSRF cookie, so set the Vary header.
                patch_vary_headers(response, ('Cookie',))

                # Since the content has been modified, any Etag will now be
                # incorrect.  We could recalculate, but only if we assume that
                # the Etag was set by CommonMiddleware. The safest thing is just
                # to delete. See bug #9163
                del response['ETag']
        return response
Ejemplo n.º 26
0
def content_negotiate(views, default=None):
    """
    Provides the plumbing for a request to be routed to the best handler method
    depending on it's HTTP Accept header value.

    The available handlers should be provided as a dictionary where keys are
    mimetypes, and values are view callables.

    If there are no matches, the ``default`` view is called, which if not
    provided falls back to returning a ``HttpResponseNotAcceptable`` (HTTP 406)
    response.

    Example usage:
    >>> # This will return a new view function, suitable for use in a
    >>> # `django.conf.urls.url` definition.
    >>> content_negotiate({
    ...     'text/html': user_friendly_view,
    ...     'application/json': machine_friendly_view,
    ... }, default=user_friendly_view)
    """
    if default is None:
        default = lambda *args, **kwargs: HttpResponseNotAcceptable()

    def handle(request, *args, **kwargs):
        try:
            key = mimeparse.best_match(views.keys(), request.META["HTTP_ACCEPT"])
            handler = views[key]
        except KeyError, IndexError:
            handler = default
        response = handler(request, *args, **kwargs)
        patch_vary_headers(response, ("Accept",))
        return response
Ejemplo n.º 27
0
def _process_response(request, response):
	from django.utils.text  import compress_string
	from django.utils.cache import patch_vary_headers
	import re
	from datetime import datetime, timedelta

	if not response.has_header('Expires') or not response.has_header('Cache-Control'):
#		response['Expires'] = (datetime.now() + timedelta(days=3)).strftime('%A %d %b %Y 00:00:00 GMT')
		response['Cache-Control'] = 'public, must-revalidate'

	# It's not worth compressing non-OK or really short responses.
	if response.status_code != 200 or len(response.content) < 200:
		return response
			
	patch_vary_headers(response, ('Accept-Encoding',))
			
	# Avoid gzipping if we've already got a content-encoding.
	if response.has_header('Content-Encoding'):
		return response
			
	# MSIE have issues with gzipped respones of various content types.
	if "msie" in request.META.get('HTTP_USER_AGENT', '').lower():
		ctype = response.get('Content-Type', '').lower()
		if not ctype.startswith("text/") or "javascript" in ctype:
			return response
			
	ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
	if 'gzip' not in ae:
		return response
			
	response.content = compress_string(response.content)
	response['Content-Encoding'] = 'gzip'
	response['Content-Length'] = str(len(response.content))
	return response
Ejemplo n.º 28
0
 def process_response(self, request, response):
     # We want to change the cookie, but didn't have the response in
     # process request.
     if hasattr(request, "LANG_COOKIE"):
         response.set_cookie("lang", request.LANG_COOKIE)
     patch_vary_headers(response, ["Accept-Language", "Cookie"])
     return response
Ejemplo n.º 29
0
    def render(self, request=None, context=None, template_name=None):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        request, context, template_name = self.get_render_params(request, context, template_name)

        self.set_renderers()

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in request.renderers:
            response = renderer(request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None
        for key, value in additional_headers.iteritems():
            response[key] = value

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept',))
        return response
Ejemplo n.º 30
0
    def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(
                request.path_info, supported=self._supported_languages
        )
        if (response.status_code == 404 and not language_from_path
                and self.is_language_prefix_patterns_used()):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                language_url = "%s://%s/%s%s" % (
                    request.is_secure() and 'https' or 'http',
                    request.get_host(), language, request.get_full_path())
                return HttpResponseRedirect(language_url)

        if not (self.is_language_prefix_patterns_used()
                and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Ejemplo n.º 31
0
 def _set_token(self, request, response):
     if settings.CSRF_USE_SESSIONS:
         request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
     else:
         response.set_cookie(
             settings.CSRF_COOKIE_NAME,
             request.META['CSRF_COOKIE'],
             max_age=settings.CSRF_COOKIE_AGE,
             domain=settings.CSRF_COOKIE_DOMAIN,
             path=settings.CSRF_COOKIE_PATH,
             secure=settings.CSRF_COOKIE_SECURE,
             httponly=settings.CSRF_COOKIE_HTTPONLY,
             samesite=settings.CSRF_COOKIE_SAMESITE,
         )
         # Set the Vary header since content varies with the CSRF cookie.
         patch_vary_headers(response, ('Cookie',))
Ejemplo n.º 32
0
def _mainview(request, view_data, **criterias):
    response, site, cachekey = view_data
    if not response:
        ctx = fjlib.page_context(request, site, **criterias)
        response = render_to_response(u'feedjack/{0}/post_list.html'.format(
            site.template),
                                      ctx,
                                      context_instance=RequestContext(request))
        # per host caching, in case the cache middleware is enabled
        patch_vary_headers(response, ['Host'])
        if site.use_internal_cache:
            fjcache.cache_set(site, cachekey,
                              (response, ctx_get(ctx, 'last_modified')))
    else:
        response = response[0]
    return response
Ejemplo n.º 33
0
 def process_response(self, request, response):
     if getattr(request, 'API', False) and response.status_code < 500:
         devices = []
         for device in ('GAIA', 'MOBILE', 'TABLET'):
             if getattr(request, device, False):
                 devices.append(device.lower())
         filters = (
             ('carrier', get_carrier() or ''),
             ('device', devices),
             ('lang', request.LANG),
             ('pro', request.GET.get('pro', '')),
             ('region', request.REGION.slug),
         )
         response['API-Filter'] = urlencode(filters, doseq=True)
         patch_vary_headers(response, ['API-Filter'])
     return response
Ejemplo n.º 34
0
 def dispatch(self, request, *args, **kwargs):
     response = super(HttpCacheMixin,
                      self).dispatch(request, *args, **kwargs)
     if self.cacheable(request, response):
         last_modified = self.get_last_modified()
         if last_modified is not None:
             response['Last-Modified'] = last_modified
         etag = self.get_etag()
         if etag is not None:
             response['ETag'] = etag
         cache_timeout = int(self.get_cache_timeout())
         patch_response_headers(response, cache_timeout)
         cache_varies = self.get_cache_varies()
         if len(cache_varies):
             patch_vary_headers(response, cache_varies)
     return response
Ejemplo n.º 35
0
def blogroll(request, btype):
    'View that handles the generation of blogrolls.'
    response, site, cachekey = initview(request)
    if response: return response[0]

    template = loader.get_template('feedjack/{0}.xml'.format(btype))
    ctx = dict()
    fjlib.get_extra_context(site, ctx)
    ctx = Context(ctx)
    response = HttpResponse(template.render(ctx),
                            content_type='text/xml; charset=utf-8')

    patch_vary_headers(response, ['Host'])
    fjcache.cache_set(site, cachekey,
                      (response, ctx_get(ctx, 'last_modified')))
    return response
Ejemplo n.º 36
0
    def process_response(self, request, response):

        if hasattr(
                request, 'response_handler'
        ):  # if it has response_handler defined, by construction it also has the session
            session_headers = request.response_handler(request.session, None,
                                                       [], None)
            for k, v in session_headers:
                response[k] = v
            request.response_handler = None
        if hasattr(request, 'session') and request.session.is_accessed():
            from django.utils.cache import patch_vary_headers
            logging.info("Varying")
            patch_vary_headers(response, ('Cookie', ))

        return response
Ejemplo n.º 37
0
    def render(self, request, context, template_name):
        """
        Returns a HttpResponse of the right media type as specified by the
        request.
        context can contain status_code and additional_headers members, to set
        the HTTP status code and headers of the request, respectively.
        template_name should lack a file-type suffix (e.g. '.html', as
        renderers will append this as necessary.
        """
        request, context, template_name = self.get_render_params(
            request, context, template_name)
        self.set_renderers()

        status_code = context.pop('status_code', httplib.OK)
        additional_headers = context.pop('additional_headers', {})

        for renderer in request.renderers:
            response = renderer(request, context, template_name)
            if response is NotImplemented:
                continue
            response.status_code = status_code
            response.renderer = renderer
            break
        else:
            tried_mimetypes = list(
                itertools.chain(*[r.mimetypes for r in request.renderers]))
            response = self.http_not_acceptable(request, tried_mimetypes)
            response.renderer = None

        for key, value in additional_headers.items():
            # My changes -- Modify location for 303 redirect
            if key == 'location' and response.renderer:
                location = '%s.%s/' % (value, response.renderer.format)
                try:
                    #location += '?page=%s' % context['page']
                    location += '?{}'.format(context['queries'])
                except KeyError:
                    pass
                response[key] = location
            else:
                response[key] = value
            # End my changes

        # We're doing content-negotiation, so tell the user-agent that the
        # response will vary depending on the accept header.
        patch_vary_headers(response, ('Accept', ))
        return response
Ejemplo n.º 38
0
    def process_response(self, request, response):
        response['X-Gzip-Delta'] = 0
        self.time = time.time()

        # It's not worth attempting to compress really short responses.
        if not response.streaming and len(response.content) < 200:
            return response

        ##Avoid gzipping if we've already got a content-encoding.
        #if response.has_header('Content-Encoding'):
        ##return response
        #del response['Content-Encoding']

        patch_vary_headers(response, ('Accept-Encoding', ))

        ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
        if not re_accepts_gzip.search(ae):
            return response

        if response.streaming:
            # Delete the `Content-Length` header for streaming content, because
            # we won't know the compressed size until we stream it.
            response.streaming_content = compress_sequence(
                response.streaming_content)
            del response['Content-Length']
        else:
            # Return the compressed content only if it's actually shorter.

            compressed_content = compress_string(response.content)
            len_compressed_content = len(compressed_content)
            len_response_content = len(response.content)

            #gzip_factor = 1.0 * len_response_content / len_compressed_content
            #response['X-Gzip-Factor'] = gzip_factor
            #
            gzip_delta = len_response_content - len_compressed_content
            response['X-Gzip-Delta'] = gzip_delta
            if gzip_delta < 0:
                return response
            response.content = compressed_content
            response['Content-Length'] = str(len(response.content))

        if response.has_header('ETag'):
            response['ETag'] = re.sub('"$', ';gzip"', response['ETag'])
        response['Content-Encoding'] = 'gzip'

        return response
Ejemplo n.º 39
0
def project_vocabs(request, uuid, return_media=None):
    """ Provides a RDF serialization, defaulting to a
        JSON-LD context for
        the data in a project. This will include
        a graph object that has annotations
        annotations of predicates and types
    """
    proj_context = ProjectContext(uuid, request)
    if 'hashes' in request.GET:
        proj_context.assertion_hashes = True
    if not proj_context.manifest:
        raise Http404
    req_neg = RequestNegotiation('application/json')
    req_neg.supported_types = ['application/ld+json']
    req_neg.supported_types += RDF_SERIALIZATIONS
    if 'HTTP_ACCEPT' in request.META:
        req_neg.check_request_support(request.META['HTTP_ACCEPT'])
    if return_media:
        req_neg.check_request_support(return_media)
        req_neg.use_response_type = return_media
    # Associate the request media type with the request so we can
    # make sure that different representations of this resource get different
    # cache responses.
    request.content_type = req_neg.use_response_type
    if not req_neg.supported:
        # client wanted a mimetype we don't support
        response = HttpResponse(req_neg.error_message,
                                content_type=req_neg.use_response_type +
                                "; charset=utf8",
                                status=415)
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response
    json_ld = proj_context.make_context_and_vocab_json_ld()
    # Check first if the output is requested to be an RDF format
    graph_output = graph_serialize(req_neg.use_response_type, json_ld)
    if graph_output:
        # Return with some sort of graph output
        response = HttpResponse(graph_output,
                                content_type=req_neg.use_response_type +
                                "; charset=utf8")
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response
    # We're outputing JSON
    json_output = json.dumps(json_ld, indent=4, ensure_ascii=False)
    if 'callback' in request.GET:
        funct = request.GET['callback']
        response = HttpResponse(funct + '(' + json_output + ');',
                                content_type='application/javascript' +
                                "; charset=utf8")
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response
    else:
        response = HttpResponse(json_output,
                                content_type=req_neg.use_response_type +
                                "; charset=utf8")
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response
Ejemplo n.º 40
0
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                response = callback(request, *args, **kwargs)

                varies = getattr(self._meta.cache, "varies", [])

                if varies:
                    patch_vary_headers(response, varies)

                if self._meta.cache.cacheable(request, response):
                    if self._meta.cache.cache_control():
                        patch_cache_control(response, **self._meta.cache.cache_control())

                if request.is_ajax() and not response.has_header("Cache-Control"):
                    patch_cache_control(response, no_cache=True)
                return response

            except IntegrityError as e:
                return FailedResult(msg=str(e))
            # =========except custome exception=========
            except DataFormatError as e:
                return FailedResult(msg=e.msg)
            # ==========================================
            except (BadRequest, fields.ApiFieldError) as e:
                # data = {"error": sanitize(e.args[0]) if getattr(e, 'args') else ''}
                # =========except custome exception=========
                return FailedResult(msg=sanitize(e.args[0]) if getattr(e, 'args') else '')
                # return self.error_response(request, data, response_class=http.HttpBadRequest)
                # ==========================================
            except ValidationError as e:
                # data = {"error": sanitize(e.messages)}
                # =========except custome exception=========
                return FailedResult(msg=sanitize(e.messages))
                # return self.error_response(request, data, response_class=http.HttpBadRequest)
                # ==========================================
            except Exception as e:
                if hasattr(e, 'response') and isinstance(e.response, HttpResponse):
                    # =========except custome exception=========
                    return e.response
                # ==========================================

                if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
                    raise
                if request.META.get('SERVER_NAME') == 'testserver':
                    raise
                return self._handle_500(request, e)
Ejemplo n.º 41
0
def html_view(request, uuid):
    request = RequestNegotiation().anonymize_request(request)
    # Handle some content negotiation for the item.
    req_neg = RequestNegotiation('text/html')
    req_neg.supported_types = []
    if 'HTTP_ACCEPT' in request.META:
        req_neg.check_request_support(request.META['HTTP_ACCEPT'])
    if not req_neg.supported:
        # The client may be wanting a non-HTML representation, so
        # use the following function to get it.
        return items_graph(request, uuid, item_type=ITEM_TYPE)
    ocitem = OCitem()
    ocitem.get_item(uuid)
    if not ocitem.manifest:
        # Did not find a record for the table, check for redirects
        r_url = RedirectURL()
        r_ok = r_url.get_direct_by_type_id(ITEM_TYPE, uuid)
        if r_ok:
            # found a redirect!!
            return redirect(r_url.redirect, permanent=r_url.permanent)
        # raise Http404
        raise Http404
    # check to see if there's related data via API calls. Add if so.
    request.uuid = ocitem.manifest.uuid
    request.project_uuid = ocitem.manifest.project_uuid
    request.item_type = ocitem.manifest.item_type
    subj_s = SubjectSupplement(ocitem.json_ld)
    ocitem.json_ld = subj_s.get_catal_related()
    rp = RootPath()
    base_url = rp.get_baseurl()
    temp_item = TemplateItem(request)
    temp_item.read_jsonld_dict(ocitem.json_ld)
    template = loader.get_template('subjects/view.html')
    if not temp_item.view_permitted:
        # The client is not allowed to see this.
        template = loader.get_template('items/view401.html')
        context = {
            'item': temp_item,
            'base_url': base_url,
            'user': request.user
        }
        return HttpResponse(template.render(context, request), status=401)
    # The client is allowd to see the current item.
    context = {'item': temp_item, 'base_url': base_url, 'user': request.user}
    response = HttpResponse(template.render(context, request))
    patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
    return response
    def process_response(self, request, response):
        """
        Add the respective CORS headers
        """
        enabled = getattr(request, '_cors_enabled', None)
        if enabled is None:
            enabled = self.is_enabled(request)

        if not enabled:
            return response

        patch_vary_headers(response, ['Origin'])

        origin = request.META.get('HTTP_ORIGIN')
        if not origin:
            return response

        # todo: check hostname from db instead
        url = urlparse(origin)

        if conf.CORS_ALLOW_CREDENTIALS:
            response[ACCESS_CONTROL_ALLOW_CREDENTIALS] = 'true'

        if (not conf.CORS_ORIGIN_ALLOW_ALL
                and not self.origin_found_in_white_lists(origin, url)
                and not self.origin_found_in_model(url)
                and not self.check_signal(request)):
            return response

        if conf.CORS_ORIGIN_ALLOW_ALL and not conf.CORS_ALLOW_CREDENTIALS:
            response[ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
        else:
            response[ACCESS_CONTROL_ALLOW_ORIGIN] = origin

        if len(conf.CORS_EXPOSE_HEADERS):
            response[ACCESS_CONTROL_EXPOSE_HEADERS] = ', '.join(
                conf.CORS_EXPOSE_HEADERS)

        if request.method == 'OPTIONS':
            response[ACCESS_CONTROL_ALLOW_HEADERS] = ', '.join(
                conf.CORS_ALLOW_HEADERS)
            response[ACCESS_CONTROL_ALLOW_METHODS] = ', '.join(
                conf.CORS_ALLOW_METHODS)
            if conf.CORS_PREFLIGHT_MAX_AGE:
                response[ACCESS_CONTROL_MAX_AGE] = conf.CORS_PREFLIGHT_MAX_AGE

        return response
Ejemplo n.º 43
0
    def __call__(self, request):
        headers = {
            'public': True,
            'max-age': 60 * 5,  # 5 minutes, 300 seconds
            'stale-while-revalidate': 60 * 5,  # 5 minutes, 300 seconds
            'stale-if-error': (60 * 60) * 24,  # 1 day, 86400 seconds
        }

        response = self.get_response(request)

        # skip patching cache headers if already explicitly set
        if 'Cache-Control' not in response:
            patch_cache_control(response, **headers)

        patch_vary_headers(response, ['Accept'])

        return response
Ejemplo n.º 44
0
def query_html(request, spatial_context=None):
    """HTML representation for searching Open Context """

    request_dict = utilities.make_request_obj_dict(
        request, spatial_context=spatial_context)
    response_dict = process_solr_query(request_dict.copy())

    req_neg = RequestNegotiation('text/html')
    req_neg.supported_types = [
        'application/json',
        'application/ld+json',
    ]

    if 'HTTP_ACCEPT' in request.META:
        req_neg.check_request_support(request.META['HTTP_ACCEPT'])

    # Associate the request media type with the request so we can
    # make sure that different representations of this resource get different
    # cache responses.
    request.content_type = req_neg.use_response_type
    if not req_neg.supported:
        # Client wanted a mimetype we don't support
        response = HttpResponse(req_neg.error_message,
                                content_type=req_neg.use_response_type +
                                "; charset=utf8",
                                status=415)
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response

    if req_neg.use_response_type.endswith('json'):
        return make_json_response(request, req_neg, response_dict)

    rp = RootPath()
    # Disable the search template and just use vue with the JSON
    # API.
    # search_temp = SearchTemplate(response_dict.copy())
    context = {
        'st': response_dict.copy(),
        'base_url': rp.get_baseurl(),
        'api_url': response_dict.get('id'),
        'configs': configs,
    }
    template = loader.get_template('search_vue/view.html')
    response = HttpResponse(template.render(context, request))
    patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
    return response
Ejemplo n.º 45
0
    def process_response(self, request, response):
        # If request.session was modified, or if response.session was set, save
        # those changes and set a session cookie.
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if modified:
                patch_vary_headers(response, ('Cookie', ))
            if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and \
               ((len(set(request.session.keys()) & MIN_COOKIE_KEYS) > 0) or \
                ('signout' in request.path)):
                if request.session.session_key:
                    session_key = request.session.session_key
                else:
                    obj = Session.objects.get_new_session_object()
                    session_key = obj.session_key

                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
                    max_age = None
                    expires = None
                else:
                    max_age = settings.SESSION_COOKIE_AGE
                    expires = datetime.datetime.strftime(
                        datetime.datetime.utcnow() + datetime.timedelta(
                            seconds=settings.SESSION_COOKIE_AGE),
                        "%a, %d-%b-%Y %H:%M:%S GMT")
                if 'signout' in request.path:
                    mem_db.delete(mem_db_key(session_key))
                else:
                    mem_db.set(mem_db_key(session_key), '1',
                               settings.SESSION_COOKIE_AGE)
                new_session = Session.objects.save(
                    session_key, request.session._session,
                    datetime.datetime.now() +
                    datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
                response.set_cookie(settings.SESSION_COOKIE_NAME,
                                    session_key,
                                    max_age=max_age,
                                    expires=expires,
                                    domain=settings.SESSION_COOKIE_DOMAIN,
                                    secure=settings.SESSION_COOKIE_SECURE
                                    or None)
        return response
Ejemplo n.º 46
0
    def __call__(self, request):
        if get_authorization_header(request) is not None:
            if not hasattr(request, 'user') or request.user.is_anonymous:
                try:
                    user = authenticate(request=request)
                except JSONWebTokenError as err:
                    return JsonResponse({'errors': [{
                        'message': str(err)
                    }]},
                                        status=401)

                if user is not None:
                    request.user = request._cached_user = user

        response = self.get_response(request)
        patch_vary_headers(response, ('Authorization', ))
        return response
Ejemplo n.º 47
0
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie or delete
     the session cookie if the session has been emptied.
     """
     try:
         accessed = request.session.accessed
         modified = request.session.modified
         empty = request.session.is_empty()
     except AttributeError:
         pass
     else:
         # First check if we need to delete this cookie.
         # The session should be deleted only if the session is entirely empty
         if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
             response.delete_cookie(settings.SESSION_COOKIE_NAME,
                 domain=settings.SESSION_COOKIE_DOMAIN)
         else:
             if accessed:
                 patch_vary_headers(response, ('Cookie',))
             if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                 # Save the session data and refresh the client cookie.
                 # Skip session save for 500 responses, refs #3881.
                 if response.status_code != 500:
                     try:
                         request.session.save()
                     except UpdateError:
                         # The user is now logged out; redirecting to same
                         # page will result in a redirect to the login page
                         # if required.
                         return redirect(request.path)
                     response.set_cookie(settings.SESSION_COOKIE_NAME,
                             request.session.session_key, max_age=max_age,
                             expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                             path=settings.SESSION_COOKIE_PATH,
                             secure=settings.SESSION_COOKIE_SECURE or None,
                             httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Ejemplo n.º 48
0
    def process_request(self, request):
        # Find locale, app
        prefixer = urlresolvers.Prefixer(request)
        redirect_type = HttpResponsePermanentRedirect
        urlresolvers.set_url_prefix(prefixer)
        full_path = prefixer.fix(prefixer.shortened_path)
        # In mkt, don't vary headers on User-Agent.
        with_app = not getattr(settings, 'MARKETPLACE', False)

        if 'lang' in request.GET:
            # Blank out the locale so that we can set a new one.  Remove lang
            # from query params so we don't have an infinite loop.
            prefixer.locale = ''
            new_path = prefixer.fix(prefixer.shortened_path)
            query = dict((smart_str(k), request.GET[k]) for k in request.GET)
            query.pop('lang')
            return redirect_type(urlparams(new_path, **query))

        if full_path != request.path:
            query_string = request.META.get('QUERY_STRING', '')
            full_path = urllib.quote(full_path.encode('utf-8'))

            if query_string:
                full_path = "%s?%s" % (full_path, query_string)

            response = redirect_type(full_path)
            # Cache the redirect for a year.
            if not settings.DEBUG:
                patch_cache_control(response, max_age=60 * 60 * 24 * 365)

            # Vary on Accept-Language or User-Agent if we changed the locale or
            # app.
            old_app = prefixer.app
            old_locale = prefixer.locale
            new_locale, new_app, _ = prefixer.split_path(full_path)

            if old_locale != new_locale:
                patch_vary_headers(response, ['Accept-Language'])
            if with_app and old_app != new_app:
                patch_vary_headers(response, ['User-Agent'])
            return response

        request.path_info = '/' + prefixer.shortened_path
        tower.activate(prefixer.locale)
        request.APP = amo.APPS.get(prefixer.app, amo.FIREFOX)
        request.LANG = prefixer.locale
Ejemplo n.º 49
0
    def process_response(
        self, request: HttpRequest, response: HttpResponse
    ) -> HttpResponse:
        if (
            response.has_header("Content-Encoding")
            or not self._accepts_brotli_encoding(request)
            or (
            not response.streaming
            and len(response.content) < MIN_LEN_FOR_RESPONSE_TO_PROCESS
        )
        ):
            # ---------
            # 1) brotlipy doesn't support streaming compression, see: https://github.com/google/brotli/issues/191
            # 2) Avoid brotli if we've already got a content-encoding.
            # 3) Client doesn't support brotli
            # 4) It's not worth attempting to compress really short responses.
            #    This was taken from django GZipMiddleware.
            # ---------
            return response

        patch_vary_headers(response, ("Accept-Encoding",))

        if response.streaming:
            compressed_content = self.compress_stream(response.streaming_content)
            response.streaming_content = compressed_content

            # Delete the `Content-Length` header for streaming content, because
            # we won't know the compressed size until we stream it.
            del response["Content-Length"]
        else:
            compressed_content = brotli.compress(response.content)

            # Return the compressed content only if it's actually shorter.
            if len(compressed_content) >= len(response.content):
                return response

            response.content = compressed_content
            response["Content-Length"] = str(len(compressed_content))

        if response.has_header("ETag"):
            response["ETag"] = re.sub(r"\"$", r";br\"", response["ETag"])

        response["Content-Encoding"] = "br"

        return response
Ejemplo n.º 50
0
    def wrapped(request, *args, api=False, **kwargs):
        if api and not api_hybrid:
            raise Exception('API call on a view without api_hybrid!')

        if not can_access_editor(request):
            raise PermissionDenied

        request.changeset = ChangeSet.get_for_request(request, select_related)

        if api:
            request.is_delete = request.method == 'DELETE'
            return call_api_hybrid_view_for_api(func, request, *args, **kwargs)

        ajax = request.is_ajax() or 'ajax' in request.GET
        if not ajax:
            request.META.pop('HTTP_IF_NONE_MATCH', None)

        if api_hybrid:
            response = call_api_hybrid_view_for_html(func, request, *args,
                                                     **kwargs)
        else:
            response = func(request, *args, **kwargs)

        if ajax:
            if isinstance(response, HttpResponseRedirect):
                return render(request, 'editor/redirect.html',
                              {'target': response['location']})
            if not isinstance(response, HttpResponseNotModified):
                response.write(
                    render(request, 'editor/fragment_nav.html', {}).content)
                if request.mobileclient:
                    response.write(
                        render(request,
                               'editor/fragment_mobileclientdata.html',
                               {}).content)
            response['Cache-Control'] = 'no-cache'
            patch_vary_headers(response, ('X-Requested-With', ))
            return response
        if isinstance(response, HttpResponseRedirect):
            return response
        response = render(request, 'editor/map.html',
                          {'content': response.content.decode()})
        response['Cache-Control'] = 'no-cache'
        patch_vary_headers(response, ('X-Requested-With', ))
        return response
Ejemplo n.º 51
0
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie', ))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 500 responses, refs #3881.
                if response.status_code != 500:

                    if not hasattr(settings, "MULTI_TENANCY_DEFAULT_SCHEMA"):
                        raise (Exception(
                            "It look like you forgot create variable name 'MULTI_TENANCY_DEFAULT_SCHEMA' settings"
                        ))
                    schema = settings.MULTI_TENANCY_DEFAULT_SCHEMA
                    import threading
                    ct = threading.currentThread()
                    if hasattr(ct, "__current_schema__"):
                        schema = ct.__current_schema__
                    request.session.save(schema=schema)
                    response.set_cookie(
                        settings.SESSION_COOKIE_NAME,
                        request.session.session_key,
                        max_age=max_age,
                        expires=expires,
                        domain=settings.SESSION_COOKIE_DOMAIN,
                        path=settings.SESSION_COOKIE_PATH,
                        secure=settings.SESSION_COOKIE_SECURE or None,
                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response
Ejemplo n.º 52
0
def buildfeed(request, feedclass, view_data):
    # TODO: quite a mess, can't it be handled with a default feed-views?
    response, site, cachekey = view_data
    if response: return response[0]

    feed_title = site.title
    if request.GET.get('feed_id'):
        try:
            feed_id = request.GET.get('feed_id')
            feed_title = u'{0} - {1}'.format(
                models.Feed.objects.get(id=feed_id).title, feed_title )
        except ObjectDoesNotExist:
            raise Http404("no such feed") # no such feed
        except ValueError: # id not numeric
            raise Http404("non-numeric feed_id")
    object_list = fjlib.get_page(request, site)['posts']

    feed = feedclass( title=feed_title, link=site.url,
        description=site.description, feed_url=u'{0}/{1}'.format(site.url, '/feed/rss/') )
    last_modified = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
    for post in object_list:
        # Enclosures are not created here, as these have somewhat unpredictable format,
        #  and don't always fit Django's url+length+type style - href+title links, for instance.
        feed.add_item(
            title = u'{0}: {1}'.format(post.feed.name, post.title),
            link = post.link,
            description = fjlib.html_cleaner(post.content),
            author_email = post.author_email,
            author_name = post.author,
            pubdate = post.date_created,
            updateddate = post.date_modified,
            unique_id = post.link,
            categories = [tag.name for tag in post.tags.all()] )
        if post.date_updated > last_modified: last_modified = post.date_updated

    response = HttpResponse(content_type=feed.mime_type)

    # Per-host caching
    patch_vary_headers(response, ['Host'])

    feed.write(response, 'utf-8')
    if site.use_internal_cache:
        fjcache.cache_set(
            site, cachekey, (response, last_modified) )
    return response
Ejemplo n.º 53
0
def blogroll(request, btype):
    """ View that handles the generation of blogrolls.
    """

    response, site, cachekey, sfeeds_obj, sfeeds_ids = initview(request)
    if response:
        return response

    template = loader.get_template('feedjack/%s.xml' % btype)
    ctx = {}
    fjlib.get_extra_content(site, sfeeds_ids, ctx)
    ctx = Context(ctx)
    response = HttpResponse(template.render(ctx) , \
      content_type='text/xml; charset=utf-8')

    patch_vary_headers(response, ['Host'])
    fjcache.cache_set(site, cachekey, response)
    return response
Ejemplo n.º 54
0
    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Encoding', ))

        # Avoid gzipping if we've already got a content-encoding or if the
        # content-type is Javascript (silly IE...)
        is_js = "javascript" in response.headers.get('Content-Type',
                                                     '').lower()
        if response.has_header('Content-Encoding') or is_js:
            return response

        ae = request.META.get('HTTP_ACCEPT_ENCODING', '')
        if not re_accepts_gzip.search(ae):
            return response

        response.content = compress_string(response.content)
        response['Content-Encoding'] = 'gzip'
        response['Content-Length'] = str(len(response.content))
        return response
Ejemplo n.º 55
0
    def process_response(self, request, response):
        """
        Notify the caching system to cache output based on HTTP_HOST as well as request
        """
        if getattr(request, "urlconf", None):
            patch_vary_headers(response, ('Host', ))
            # reset TEMPLATE_DIRS because we unconditionally add to it when
        # processing the request

        settings.ROOT_URLCONF = ROOT_URLCONF.value
        self.logger.debug('applied ROOT_URLCONF=%s' % settings.ROOT_URLCONF)

        try:
            if self._old_TEMPLATE_DIRS is not None:
                settings.TEMPLATE_DIRS = self._old_TEMPLATE_DIRS
        except AttributeError:
            pass
        return response
Ejemplo n.º 56
0
def handle_auth_cookies(request, response, token_key):
    rotate_csrf_token(request)
    response.set_cookie(
        "authToken",
        token_key,
        max_age=1209600,  # 2 weeks, in seconds
        domain=None,
        path='/',
        secure=settings.SECURE_SSL_REDIRECT,
        httponly=False,
        samesite='Lax',
    )
    patch_vary_headers(
        response,
        ('Cookie',
         ))  # Set the Vary header since content varies with the CSRF cookie.

    return response
Ejemplo n.º 57
0
def make_json_response(request, req_neg, response_dict):
    """Makes a JSON response with content negotiation"""
    json_output = json.dumps(response_dict, indent=4, ensure_ascii=False)
    if 'callback' in request.GET:
        # The JSON-P response
        funct = request.GET['callback']
        response = HttpResponse(
            '{funct}({json_output});'.format(funct=funct,
                                             json_output=json_output),
            content_type='application/javascript' + "; charset=utf8")
        patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
        return response

    response = HttpResponse(json_output,
                            content_type=req_neg.use_response_type +
                            "; charset=utf8")
    patch_vary_headers(response, ['accept', 'Accept', 'content-type'])
    return response
Ejemplo n.º 58
0
def fetch_render_snippets(request, **kwargs):
    """Fetch snippets for the client and render them immediately."""
    client = Client(**kwargs)
    matching_snippets = (Snippet.cached_objects.filter(
        disabled=False).match_client(client).order_by(
            'priority').select_related('template').filter_by_available())

    response = render(request, 'base/fetch_snippets.html', {
        'snippets': matching_snippets,
        'client': client,
        'locale': client.locale,
    })

    # ETag will be a hash of the response content.
    response['ETag'] = hashlib.sha256(response.content).hexdigest()
    patch_vary_headers(response, ['If-None-Match'])

    return response
def persist_apple_session(request, response):
    """
    Save `request.apple_login_session` and set the cookie
    """
    patch_vary_headers(response, ('Cookie',))
    request.apple_login_session.save()
    response.set_cookie(
        APPLE_SESSION_COOKIE_NAME,
        request.apple_login_session.session_key,
        max_age=None,
        expires=None,
        domain=settings.SESSION_COOKIE_DOMAIN,
        # The cookie is only needed on this endpoint
        path=response.url,
        secure=True,
        httponly=None,
        samesite=settings.SESSION_COOKIE_SAMESITE,
    )
Ejemplo n.º 60
0
    def process_response(self, request, response):
        domain = Site.objects.get_current().domain.split(':')[0]
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
        except AttributeError:
            pass
        else:
            if empty:
                response.delete_cookie(
                    settings.SESSION_COOKIE_NAME,
                    path=settings.SESSION_COOKIE_PATH,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                )
            if accessed:
                patch_vary_headers(response, ("Cookie", ))
            if (modified or settings.SESSION_SAVE_EVERY_REQUEST
                ) and not empty and response.status_code != 500:

                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires = http_date(time() + max_age)
                try:
                    request.session.save()
                except UpdateError:
                    raise SuspiciousOperation(
                        "The request's session was deleted before the "
                        "request completed. The user may have logged "
                        "out in a concurrent request, for example.")
                response.set_cookie(
                    settings.SESSION_COOKIE_NAME,
                    request.session.session_key,
                    max_age=max_age,
                    expires=expires,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                    path=settings.SESSION_COOKIE_PATH,
                    secure=settings.SESSION_COOKIE_SECURE,
                    httponly=settings.SESSION_COOKIE_HTTPONLY,
                )
        return response