Created
March 22, 2014 16:34
-
-
Save ckinsey/9709984 to your computer and use it in GitHub Desktop.
Require SSL for Django views via a decorator. You'll need some setup in your web server to support the request.is_secure() method--see the Django docs.
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
from functools import wraps | |
from django.conf import settings | |
from django.http import HttpResponseRedirect | |
def require_ssl(view): | |
""" | |
Decorator that requires an SSL connection. If the current connection is not SSL, we redirect to the SSL version of | |
the page. | |
""" | |
@wraps(view) | |
def wrapper(request, *args, **kwargs): | |
if not settings.DEBUG and not request.is_secure(): | |
# Redirect! | |
target_url = "https://" + request.META['HTTP_HOST'] + request.path_info | |
return HttpResponseRedirect(target_url) | |
return view(request, *args, **kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment