Skip to content

redirect

django_spire.core.redirect

__all__ = ['safe_redirect_url'] module-attribute

safe_redirect_url

Generates a safe redirect URL based on the request's GET parameters and HTTP_REFERER, ensuring that the URL is valid and safe. If neither the return URL nor the referer is valid, a fallback URL is returned.

Parameters:

  • request (WSGIRequest) –

    The WSGIRequest object containing GET and META data.

  • fallback (str, default: '/' ) –

    The fallback URL to use if no valid redirect URL is found; defaults to '/'.

Returns:

  • str

    A safe redirect URL.

Source code in django_spire/core/redirect/safe_redirect.py
def safe_redirect_url(request: WSGIRequest, fallback: str = '/') -> str:
    """
    Generates a safe redirect URL based on the request's GET parameters and
    HTTP_REFERER, ensuring that the URL is valid and safe. If neither the
    return URL nor the referer is valid, a fallback URL is returned.

    :param request: The WSGIRequest object containing GET and META data.
    :param fallback: The fallback URL to use if no valid redirect URL is found; defaults to '/'.
    :return: A safe redirect URL.
    """

    allowed_hosts = {request.get_host()}

    if hasattr(settings, 'ALLOWED_HOSTS'):
        allowed_hosts.update(settings.ALLOWED_HOSTS)

    return_url = request.GET.get('return_url')

    if is_url_valid_and_safe(url=return_url, allowed_hosts=allowed_hosts):
        return resolve_url(return_url)

    referer = request.META.get('HTTP_REFERER')

    if is_url_valid_and_safe(url=referer, allowed_hosts=allowed_hosts):
        url = urlparse(referer)
        query_string = urlencode(parse_qs(url.query), doseq=True)
        path = resolve_url(url.path)

        full = (
            url.scheme,
            url.netloc,
            path,
            '',
            query_string,
            url.fragment
        )

        return urlunparse(full)

    if not is_url_valid_and_safe(url=fallback, allowed_hosts=allowed_hosts):
        fallback = '/'

    return fallback