Skip to content

Instantly share code, notes, and snippets.

@allanlei
Last active December 16, 2015 03:29
Show Gist options
  • Save allanlei/5370094 to your computer and use it in GitHub Desktop.
Save allanlei/5370094 to your computer and use it in GitHub Desktop.
Force HTTPS middleware. Parts taken from rdegges/django-sslify and kennethreitz / flask-sslify. Excludes checking for HTTP_X_FORWARDED_PROTO, as that should be handled by Django 1.4+ by SECURE_PROXY_SSL_HEADER setting. For Django 1.4<, the SECURE_PROXY_SSL_HEADER should be implemented through a sperate middleware. Should be using django-appconf …
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
SSLIFY_ENABLED = getattr(settings, 'SSLIFY_ENABLED', not settings.DEBUG)
SSLIFY_HSTS_AGE = int(getattr(settings, 'SSLIFY_HSTS_AGE', 60 * 60 * 24 * 365))
SSLIFY_INCLUDE_SUBDOMAINS = getattr(settings, 'SSLIFY_INCLUDE_SUBDOMAINS', False)
SSLIFY_PERMANENT = getattr(settings, 'SSLIFY_PERMANENT', False)
if SSLIFY_PERMANENT:
from django.http import HttpResponsePermanentRedirect as HttpResponseClass
else:
from django.http import HttpResponseRedirect as HttpResponseClass
class SSLifyMiddleware(object):
def __init__(self, *args, **kwargs):
if not SSLIFY_ENABLED:
raise MiddlewareNotUsed()
self.hsts_header = 'max-age={0}'.format(SSLIFY_HSTS_AGE)
if SSLIFY_INCLUDE_SUBDOMAINS:
self.hsts_header += '; includeSubDomains'
def process_request(self, request):
"""Redirect incoming requests to HTTPS."""
# Should we redirect?
criteria = [
request.is_secure(),
]
if not any(criteria):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace('http://', 'https://', 1)
return HttpResponseClass(secure_url)
def process_response(self, request, response):
if not response.has_header('Strict-Transport-Security'):
response['Strict-Transport-Security'] = self.hsts_header
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment