Login

SSL Decorator

Author:
pjs
Posted:
March 2, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

Wrote this some time ago when I couldn't find one already completed. Came up in the IRC channel so I decided to post it.

Easy enough to use.

from ssldecorator import ssl_required

@ssl_required def your_view(request): ''' your code here '''

You can place a variable in your settings.py to change the SSL domain (ie, if you have SSL running on secure.yourdomain.com instead of www.yourdomain.com)..

SSL_DOMAIN = 'https://secure.yourdomain.com'

Note: please include a proper URL. If https isn't used, the decorator will add it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import urlparse
from django.conf import settings
from django.http import HttpResponseRedirect


def ssl_required(view_func):
    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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.