Created
February 6, 2010 17:10
-
-
Save wolever/296820 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on http://www.djangosnippets.org/snippets/85/ | |
from django.conf import settings | |
from django.http import HttpResponseRedirect | |
from django.http import HttpResponseRedirect, get_host | |
def is_insecure(request): | |
return not request.is_secure() | |
class UseHttpsMiddleware: | |
def process_request(self, request): | |
""" If a request contains login information, make sure that request | |
is secured. """ | |
if not getattr(settings, "USE_HTTPS", False): | |
return | |
# Is someone authenticated, but the request is insecure? | |
if request.user.is_authenticated() and is_insecure(request): | |
return self._redirect_to_https(request) | |
def process_view(self, request, view_func, view_args, view_kwargs): | |
""" Allow views to request a secure connection by adding | |
{ "SSL": True } to their kwargs. For example: | |
r'^login$','login_view', {'SSL': True} """ | |
if not getattr(settings, "USE_HTTPS", False): | |
return | |
# Has this view requested SSL, but the request isn't currently SSL? | |
if view_kwargs.get("SSL") and is_insecure(request): | |
del view_kwargs["SSL"] | |
return self._redirect_to_https(request) | |
def _redirect_to_https(self, request): | |
""" Redirect the response to the same URL, but using HTTPS. """ | |
newurl = "https://%s%s" % (protocol, get_host(request), | |
request.get_full_path()) | |
if settings.DEBUG and request.method == 'POST': | |
raise RuntimeError("Django can't perform a SSL redirect while " + | |
"maintaining POST data. Structure your views " + | |
"so that redirects only occur during GETs.") | |
return HttpResponseRedirect(newurl) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment