def process_request(self, request):
        # First try to serve the static files (on /static/ and on /)
        # which is relatively fast as files are stored in a self.files dict
        if self.autorefresh:  # debug mode
            static_file = self.find_file(request.path_info)
        else:  # from the collected static files
            static_file = self.files.get(request.path_info)
        if static_file is not None:
            return self.serve(static_file, request)
        else:
            # if no file was found there are two options:

            # 1) the file is in one of the Django urls
            # (e.g. a template or the Djangoadmin)
            # so we'll let Django handle this
            # (just return and let the normal middleware take its course)
            urlconf = getattr(request, 'urlconf', None)
            if is_valid_path(request.path_info, urlconf):
                return
            if (settings.APPEND_SLASH and not request.path_info.endswith('/')
                    and is_valid_path('%s/' % request.path_info, urlconf)):
                return

            # 2) the url is handled by frontend routing
            # redirect all unknown files to the SPA root
            try:
                return self.serve(self.spa_root, request)
            except AttributeError:  # no SPA page stored yet
                self.spa_root = self.find_file('/')
                if self.spa_root:
                    return self.serve(self.spa_root, request)
    def should_redirect_with_slash(self, request):
        if request.path_info.endswith('/'):
            return False

        urlconf = getattr(request, 'urlconf', None)
        return (not is_valid_path(request.path_info, urlconf)
                and is_valid_path('%s/' % request.path_info, urlconf))
Beispiel #3
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)
            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 (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
Beispiel #4
0
    def process_exception(self, request, exception):
        '''Rewrite the URL based on settings.APPEND_SLASH and the urlconf of the current page.'''

        if isinstance(exception, Http404):
            if settings.APPEND_SLASH and not request.path_info.endswith('/'):
                page = request.pages.current

                if page:
                    script_name = page.get_absolute_url()[:-1]
                    path_info = request.path[len(script_name):]

                    urlconf = getattr(page.content,
                                      'urlconf', None) if hasattr(
                                          page, 'content') else None

                    # Check if the URL with a slash appended is resolved by the current page's urlconf
                    if (is_valid_path(path_info, urlconf)
                            or not is_valid_path(f'{path_info}/', urlconf)):
                        # Check if the URL with a slash appended resolves for something other than a page
                        match = resolve(f'{path_info}/',
                                        getattr(request, 'urlconf', None))
                        if getattr(match.func, 'view_class',
                                   None) is PageDispatcherView:
                            # Couldn't find any view that would be resolved for this URL
                            # No point redirecting to a URL that will 404
                            return None

                new_path = request.get_full_path(force_append_slash=True)
                # Prevent construction of scheme relative urls.
                new_path = escape_leading_slashes(new_path)

                return HttpResponsePermanentRedirect(new_path)
Beispiel #5
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
    def process_request(self, request):

        old_url = request.build_absolute_uri()
        # match any / followed by ? (query string present)
        # OR match / at the end of the string (no query string)
        trailing_slash_regexp = r'(\/(?=\?))|(\/$)'
        new_url = old_url

        if getattr(settings, 'APPEND_SLASH') and getattr(settings, 'REMOVE_SLASH'):
            raise ImproperlyConfigured("APPEND_SLASH and REMOVE_SLASH may not both be True.")

        # Remove slash if REMOVE_SLASH is set and the URL has a trailing slash
        # and there is no pattern for the current path
        if getattr(settings, 'REMOVE_SLASH', False) and re.search(trailing_slash_regexp, old_url):
            urlconf = getattr(request, 'urlconf', None)
            if (not is_valid_path(request.path_info, urlconf)) and is_valid_path(request.path_info[:-1], urlconf):
                new_url = re.sub(trailing_slash_regexp, '', old_url)
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL ends in a "
                    "slash and you have REMOVE_SLASH set. Django can't "
                    "redirect to the non-slash URL while maintaining POST "
                    "data. Change your form to point to %s (without a "
                    "trailing slash), or set REMOVE_SLASH=False in your "
                    "Django settings.") % (new_url))

        if new_url == old_url:
            # No redirects required.
            return
        return HttpResponsePermanentRedirect(new_url)
Beispiel #7
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 and prefixed_default_language):
            # Maybe the language code is missing in the URL? Try adding the
            # language prefix and redirecting to that URL.
            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
Beispiel #8
0
def set_language(request):
    """
    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    error.
    """
    lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
    next_url = urlsplit(request.POST.get("next")) if request.POST.get("next") else None
    if lang_code and check_for_language(lang_code):
        if next_url and is_valid_path(next_url.path):
            # If it is a recognized Kolibri path, then translate it to the new language and return it.
            next_path = urlunsplit(
                (
                    next_url[0],
                    next_url[1],
                    translate_url(next_url[2], lang_code),
                    next_url[3],
                    next_url[4],
                )
            )
        else:
            next_path = translate_url(reverse("kolibri:core:redirect_user"), lang_code)
        response = HttpResponse(next_path)
        if hasattr(request, "session"):
            request.session[LANGUAGE_SESSION_KEY] = lang_code
        # Always set cookie
        response.set_cookie(
            settings.LANGUAGE_COOKIE_NAME,
            lang_code,
            max_age=settings.LANGUAGE_COOKIE_AGE,
            path=settings.LANGUAGE_COOKIE_PATH,
            domain=settings.LANGUAGE_COOKIE_DOMAIN,
        )
    else:
        lang_code = (
            get_device_language()
            or get_accept_headers_language(request)
            or get_settings_language()
        )
        if next_url and is_valid_path(next_url.path):
            # If it is a recognized Kolibri path, then translate it using the default language code for this device
            next_path = urlunsplit(
                (
                    next_url[0],
                    next_url[1],
                    translate_url(next_url[2], lang_code),
                    next_url[3],
                    next_url[4],
                )
            )
        else:
            next_path = translate_url(reverse("kolibri:core:redirect_user"), lang_code)
        response = HttpResponse(next_path)
        if hasattr(request, "session"):
            request.session.pop(LANGUAGE_SESSION_KEY, "")
        response.delete_cookie(settings.LANGUAGE_COOKIE_NAME)
    return response
Beispiel #9
0
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is True and appending a slash to
     the request path turns an invalid path into a valid one.
     """
     if settings.APPEND_SLASH and not request.get_full_path().endswith("/"):
         urlconf = getattr(request, "urlconf", None)
         return not is_valid_path(request.path_info, urlconf) and is_valid_path("%s/" % request.path_info, urlconf)
     return False
Beispiel #10
0
 def should_redirect_with_slash(self, request):
     path = request.path_info
     # Avoid redirecting non GET requests, these would fail anyway
     if path.endswith("/") or request.method != "GET":
         return False
     urlconf = getattr(request, "urlconf", None)
     slash_path = f"{path}/"
     return not is_valid_path(path, urlconf) and is_valid_path(
         slash_path, urlconf)
Beispiel #11
0
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is True and appending a slash to
     the request path turns an invalid path into a valid one.
     """
     if settings.APPEND_SLASH and not request.path_info.endswith('/'):
         urlconf = getattr(request, 'urlconf', None)
         return (not is_valid_path(request.path_info, urlconf)
                 and is_valid_path('%s/' % request.path_info, urlconf))
     return False
Beispiel #12
0
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is False and removing a slash from
     the request path turns an invalid path into a valid one.
     """
     if not settings.APPEND_SLASH and request.path_info.endswith('/'):
         urlconf = getattr(request, 'urlconf', None)
         return (not is_valid_path(request.path_info, urlconf)
                 and is_valid_path(request.path_info[:-1], urlconf))
     return False
Beispiel #13
0
 def process_response(self, request, response):
     if (response.status_code == 404 and request.path_info.endswith('/')
             and not is_valid_path(request.path_info)
             and is_valid_path(request.path_info[:-1])):
         # Use request.path because we munged app/locale in path_info.
         newurl = request.path[:-1]
         if request.GET:
             with safe_query_string(request):
                 newurl += '?' + request.META['QUERY_STRING']
         return HttpResponsePermanentRedirect(newurl)
     return response
Beispiel #14
0
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is False and removing a slash from
     the request path turns an invalid path into a valid one.
     """
     if not settings.APPEND_SLASH and request.path_info.endswith('/'):
         urlconf = getattr(request, 'urlconf', None)
         return (
             not is_valid_path(request.path_info, urlconf) and
             is_valid_path(request.path_info[:-1], urlconf)
         )
     return False
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is True and appending a slash to
     the request path turns an invalid path into a valid one.
     """
     if settings.APPEND_SLASH and not request.path_info.endswith('/'):
         urlconf = getattr(request, 'urlconf', None)
         return (
             not is_valid_path(request.path_info, urlconf) and
             is_valid_path('%s/' % request.path_info, urlconf)
         )
     return False
Beispiel #16
0
    def __call__(self, request):
        # First get the language code, and whether this was calculated from the path
        # i.e. was this a language-prefixed URL.
        language, language_from_path = get_language_from_request_and_is_from_path(
            request)
        # If this URL has been resolved to a view, and the view is not on a language prefixed
        # URL, then the function above will return None for the language code to indicate that
        # no translation is necessary.
        if language is not None:
            # Only activate translation if there is a language code returned.
            translation.activate(language)
            request.LANGUAGE_CODE = translation.get_language()

        response = self.get_response(request)

        if language is not None:

            language = translation.get_language()

            if response.status_code == 404 and not language_from_path:
                # Maybe the language code is missing in the URL? Try adding the
                # language prefix and redirecting to that URL.
                # First get any global prefix that is being used.
                script_prefix = OPTIONS["Deployment"]["URL_PATH_PREFIX"]
                # Replace the global prefix with the global prefix and the language prefix.
                language_path = request.path_info.replace(
                    script_prefix, "%s%s/" % (script_prefix, language), 1)

                # Get the urlconf from the request, default to the global settings ROOT_URLCONF
                urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
                # Check if this is a valid path
                path_valid = is_valid_path(language_path, urlconf)
                # Check if the path is only invalid because it is missing a trailing slash
                path_needs_slash = not path_valid and (
                    settings.APPEND_SLASH and not language_path.endswith("/")
                    and is_valid_path("%s/" % language_path, urlconf))
                # If the constructed path is valid, or it would be valid with a trailing slash
                # then redirect to the prefixed path, with a trailing slash added if needed.
                if path_valid or path_needs_slash:
                    # 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 HttpResponseRedirect(language_url)

            # Add a content language header to the response if not already present.
            if "Content-Language" not in response:
                response["Content-Language"] = language

        return response
Beispiel #17
0
 def should_redirect_with_slash(self, request):
     """
     Return True if settings.APPEND_SLASH is True and appending a slash to
     the request path turns an invalid path into a valid one.
     """
     if settings.APPEND_SLASH and not request.path_info.endswith("/"):
         urlconf = getattr(request, "urlconf", None)
         if not is_valid_path(request.path_info, urlconf):
             match = is_valid_path("%s/" % request.path_info, urlconf)
             if match:
                 view = match.func
                 return getattr(view, "should_append_slash", True)
     return False
Beispiel #18
0
 def should_redirect_with_slash(self, request):
     path = request.path_info
     # Avoid redirecting non GET requests, these would fail anyway due to
     # missing parameters.
     # Redirecting on API removes authentication headers in many cases,
     # so avoid that as well.
     if (path.endswith("/") or request.method != "GET"
             or path.startswith(f"{settings.URL_PREFIX}/api")):
         return False
     urlconf = getattr(request, "urlconf", None)
     slash_path = f"{path}/"
     return not is_valid_path(path, urlconf) and is_valid_path(
         slash_path, urlconf)
 def process_response(self, request, response):
     if (response.status_code == 404 and
             request.path_info.endswith('/') and
             not is_valid_path(request.path_info) and
             is_valid_path(request.path_info[:-1])):
         # Use request.path because we munged app/locale in path_info.
         newurl = request.path[:-1]
         if request.GET:
             with safe_query_string(request):
                 newurl += '?' + request.META.get('QUERY_STRING', '')
         return HttpResponsePermanentRedirect(newurl)
     else:
         return response
    def _calculate_user_urlconf(self, request, user_settings):
        """
        :param request:
        :param user_settings:
        :return:
        """
        cache = caches[getattr(settings, 'HACS_CACHE_SETTING_NAME', HACS_CACHE_SETTING_NAME)]
        if user_settings['urlconf'] and user_settings['has_own_rules']:
            return user_settings['urlconf']

        elif user_settings['groups']:

            if user_settings['urlconf']:
                # Already inherited from group, let's check if is usable
                # otherwise will be trying from other groups
                if is_valid_path(request.path_info, user_settings['urlconf']) or \
                    (settings.APPEND_SLASH and not request.get_full_path().endswith('/') and
                         is_valid_path(request.path_info, "%s/" % user_settings['urlconf'])):
                    return user_settings['urlconf']

            _temp = None
            for group_cache_key, group_natural_key in user_settings['groups']:

                if not cache.get(group_cache_key, {}).get('urlconf', None):
                    continue

                if cache.get(group_cache_key, {}).get('urlconf') == user_settings['urlconf']:
                    # already failed, so need to go further
                    continue

                if is_valid_path(request.path_info, cache.get(group_cache_key).get('urlconf')) or \
                    (settings.APPEND_SLASH and not request.get_full_path().endswith('/') and
                         is_valid_path(request.path_info, "%s/" % cache.get(group_cache_key).get('urlconf'))):
                    user_settings.update({
                        'urlconf': cache.get(group_cache_key).get('urlconf'),
                        'allowed_http_methods': cache.get(group_cache_key).get('allowed_http_methods'),
                        'blacklisted_uri': cache.get(group_cache_key).get('blacklisted_uri'),
                        'whitelisted_uri': cache.get(group_cache_key).get('whitelisted_uri'),
                    })
                    # Update User's cache
                    cache.set(get_user_key(request), user_settings)

                    _temp = cache.get(group_cache_key).get('urlconf')
                    break

                else:
                    continue
            # @TODO: need some decision what should do if result is None
            return _temp
        else:
            return None
Beispiel #21
0
def test_urls():
    try:
        from django.urls import is_valid_path
    except ImportError:
        from django.core.urlresolvers import is_valid_path
    assert settings.ROOT_URLCONF == "pytest_django_test.urls_overridden"
    assert is_valid_path("/overridden_url/")
Beispiel #22
0
    def middleware(request):
        # TODO: DISCLAIMER!!! THIS IS A TEMPORARY HACK TO ESCAPE FROM CURRENT "DDOS ATTACK"
        # WE MUST IMPLEMENT RATE LIMIT CONTROL IN NGINX OR CLOUDFARE SO WE DON'T HAVE TO RELY ON DJANGO TO DO THAT
        agent = request.META.get("HTTP_USER_AGENT", "").lower().strip()
        if not agent or agent in settings.BLOCKED_WEB_AGENTS:
            _raise_exception(request)

        path = request.path
        if settings.APPEND_SLASH and not path.endswith("/"):
            path += "/"

        if is_valid_path(path):
            match = resolve(path)
            if getattr(match.func, RATELIMITED_VIEW_ATTR, None):
                # based in ratelimit decorator
                # https://github.com/jsocol/django-ratelimit/blob/main/ratelimit/decorators.py#L13
                if settings.RATELIMIT_ENABLE and is_ratelimited(
                        request=request,
                        group=None,
                        fn=match.func,
                        key=ratelimit_key,
                        rate=settings.RATELIMIT_RATE,
                        method=ALL,
                        increment=True,
                ):
                    _raise_exception(request)

        return get_response(request)
Beispiel #23
0
def test_urls():
    try:
        from django.urls import is_valid_path
    except ImportError:
        from django.core.urlresolvers import is_valid_path
    assert settings.ROOT_URLCONF == 'pytest_django_test.urls_overridden'
    assert is_valid_path('/overridden_url/')
def test_urls():
    try:
        from django.urls import is_valid_path
    except ImportError:
        from django.core.urlresolvers import is_valid_path
    assert settings.ROOT_URLCONF == 'django-rest-framework-api.urls'
    assert is_valid_path('/')
Beispiel #25
0
def set_language(request):
    """
    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    error.
    """
    payload = json.loads(request.body)
    lang_code = payload.get(LANGUAGE_QUERY_PARAMETER)
    next_url = urlsplit(payload.get("next")) if payload.get("next") else None
    if lang_code and lang_code in SUPPORTED_LANGUAGES:
        if next_url and is_valid_path(next_url.path):
            # If it is a recognized path, then translate it to the new language and return it.
            next_path = urlunsplit(
                (
                    next_url[0],
                    next_url[1],
                    translate_url(next_url[2], lang_code),
                    next_url[3],
                    next_url[4],
                )
            )
        else:
            # Just redirect to the base URL w/ the lang_code
            next_path = translate_url(reverse('base'), lang_code)
        response = HttpResponse(next_path)
        if hasattr(request, "session"):
            request.session[LANGUAGE_SESSION_KEY] = lang_code
    else:
        lang_code = get_language()
        if next_url and is_valid_path(next_url.path):
            # If it is a recognized path, then translate it using the default language code for this device
            next_path = urlunsplit(
                (
                    next_url[0],
                    next_url[1],
                    translate_url(next_url[2], lang_code),
                    next_url[3],
                    next_url[4],
                )
            )
        else:
            # Just redirect to the base URL w/ the lang_code, likely the default language
            next_path = translate_url(reverse('base'), lang_code)
        response = HttpResponse(next_path)
        if hasattr(request, "session"):
            request.session.pop(LANGUAGE_SESSION_KEY, "")
    return response
Beispiel #26
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
            and prefixed_default_language
        ):
            # Maybe the language code is missing in the URL? Try adding the
            # language prefix and redirecting to that URL.
            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)
                # Redirect to the language-specific URL as detected by
                # get_language_from_request(). HTTP caches may cache this
                # redirect, so add the Vary header.
                redirect = self.response_redirect_class(language_url)
                patch_vary_headers(redirect, ("Accept-Language", "Cookie"))
                return redirect

        if not (i18n_patterns_used and language_from_path):
            patch_vary_headers(response, ("Accept-Language",))
        response.headers.setdefault("Content-Language", language)
        return response
Beispiel #27
0
    def post(self, request, *args, **kwargs):
        view = self.get(request)

        # 登录成功,view 的类型是 HttpResponseRedirect
        # 帐号登录方式的用户名肯定是存在了,不然也不会成功登录,所以这里不用对用户是否存在做判断
        if isinstance(view, HttpResponseRedirect):
            # 如果当前就是登录页,那么就不要跳到登录页
            url_path = request.path if is_valid_path(request.path) is True and request.path != reverse(
                'xadmin:login') else reverse(settings.SITE_NAME)
            return HttpResponseRedirect(url_path)

        return view
Beispiel #28
0
    def get_redirect_url(self, *args, **kwargs):
        """
        重定向
        :param args:
        :param kwargs:
        :return:
        """
        if isinstance(self.request.user, AnonymousUser):
            return reverse('xadmin:login')

        self.url = self.request.user.home_page if is_valid_path(self.request.user.home_page) is True else self.url

        return super().get_redirect_url(*args, **kwargs)
Beispiel #29
0
    def process_response(self, request, response):
        language_from_path = get_language_from_path(request.path_info)

        if response.status_code == 404 and language_from_path == settings.LANGUAGE_CODE:
            urlconf = getattr(request, 'urlconf', None)
            new_path = self.strip_language(request.path_info)
            path_valid = is_valid_path(new_path, urlconf)

            if (not path_valid and settings.APPEND_SLASH
                    and not new_path.endswith('/')):
                path_valid = is_valid_path("%s/" % new_path, urlconf)

            if path_valid:
                script_prefix = get_script_prefix()
                old_path = get_script_prefix() + language_from_path + '/'
                language_url = "%s://%s%s" % (
                    request.scheme,
                    request.get_host(),
                    # replace the old path which contains language code
                    # to the script prefix without language code
                    request.get_full_path().replace(old_path, script_prefix,
                                                    1))
                return self.response_redirect_class(language_url)
        return response
Beispiel #30
0
    def middleware(request):
        path = request.get_full_path()

        if '//' in path:
            path = re.sub(r'(/)\1+', r'\1', path)
            return redirect(path, permanent=True)

        if not settings.APPEND_SLASH:
            return get_response(request)

        is_url_exempt = any(
            url.match(path.lstrip('/'))
            for url in REDIRECTS_EXTRA_SLASHES_REDIRECT_EXEMPT_URLS)

        if is_url_exempt:
            return get_response(request)

        is_url_to_redirect = all(
            [not request.GET,
             len(path) > 1, not str(path).endswith('/')])

        if is_url_to_redirect:
            urlconf = getattr(request, 'urlconf', None)

            # if path without slash is not valid - append slash
            if not is_valid_path(path, urlconf):
                path += '/'

            if is_valid_path(path, urlconf):
                return redirect(path, permanent=True)

        if path.endswith('?'):
            path = path[:-1]
            return redirect(path, permanent=True)

        return get_response(request)
    def __call__(self, request):
        response = self.get_response(request)

        if (response.status_code == 404
                and not request.path_info.startswith("/u/")
                and not is_valid_path(request.path_info)
                and User.objects.filter(username__iexact=request.path_info[1:].
                                        strip("/")).exists()
                and request.user.is_authenticated
                and request.user.userprofile.is_vouched):

            newurl = "/u" + request.path_info
            if request.GET:
                with safe_query_string(request):
                    newurl += "?" + request.META["QUERY_STRING"]
            return HttpResponseRedirect(newurl)
        return response
Beispiel #32
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)
            if settings.APPEND_SLASH and not language_path.endswith('/'):
                language_path = 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 HttpResponsePermanentRedirect(language_url)
        translation.deactivate()

        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response
Beispiel #33
0
    def process_request(self, request):
        if settings.APPEND_SLASH:
            return

        if '/admin/' in request.path:
            return

        if '/utils/login_as' in request.path:
            return

        if '/sandbox/' in request.path:
            return

        if '/__debug__/' in request.path:
            return

        if request.path_info.endswith('/'):
            urlconf = getattr(request, 'urlconf', None)

            if is_valid_path(request.path_info[:-1], urlconf):
                new_path = request.path_info[:-1]

                if request.method == 'GET':
                    if request.META['QUERY_STRING']:
                        new_path += '?' + request.META['QUERY_STRING']

                if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'):
                    raise RuntimeError(
                        "You called this URL via %(method)s, but the URL doesn't end "
                        "in a slash and you have APPEND_SLASH set. Django can't "
                        "redirect to the slash URL while maintaining %(method)s data. "
                        "Change your form to point to %(url)s (note the trailing "
                        "slash), or set APPEND_SLASH=False in your Django settings." % {
                            'method': request.method,
                            'url': request.get_host() + new_path,
                        }
                    )
                return self.response_redirect_class(new_path)
Beispiel #34
0
def test_urls():
    assert settings.ROOT_URLCONF == "septic_check.urls"
    assert is_valid_path("/sewage_info/")
def test_urls():
    assert settings.ROOT_URLCONF == "pytest_django_test.urls_overridden"
    assert is_valid_path("/overridden_url/")