Skip to content
Collin Green edited this page Jun 13, 2015 · 1 revision

SSL Tools

ssl middleware for heroku

from django.conf import settings
from django.http import HttpResponsePermanentRedirect


class SslOnlyMiddleware(object):
    """
    This is taken directly from rdegges django-sslify project with an extra
    header check to support heroku (HTTP_X_FORWARDED_PROTO).
    """
    def process_request(self, request):
        if getattr(settings, 'DISABLE_SSL', False):
            return None

        if not settings.DEBUG \
                and not request.is_secure() \
                and not request.META.get('HTTP_X_FORWARDED_PROTO', '') == 'https':
            url = request.build_absolute_uri(request.get_full_path())
            secure_url = url.replace('http://', 'https://')
            return HttpResponsePermanentRedirect(secure_url)

ssl_required decorator

from django.http import HttpResponseRedirect
from django.conf import settings


# http://djangosnippets.org/snippets/1351/
def ssl_required(view_func):
    """
    Add this to views to enforce https connections by redirecting
    any http:// requests to https:// versions.
    If SSL_DOMAIN exists in settings this will change the base domain,
    otherwise simply replaces http: with https:

    Usage:
        @ssl_required
        def view(request):
            ...
    """
    def _checkssl(request, *args, **kwargs):
        if not settings.DEBUG and not request.is_secure():
            if hasattr(settings, 'SSL_DOMAIN'):
                url_str = urlparse.urljoin(
                    settings.SSL_DOMAIN,
                    request.get_full_path()
                )
            else:
                url_str = request.build_absolute_uri()
            url_str = url_str.replace('http://', 'https://')
            return HttpResponseRedirect(url_str)

        return view_func(request, *args, **kwargs)
    return _checkssl

Clone this wiki locally