root/django/trunk/middleware/sslmiddleware.py

Revision 50, 2.0 kB (checked in by verbosus, 2 years ago)

Removed version variable: I kept forgetting to bump it up, we need a better way (maybe the svn id or something)

  • Property svn:eol-style set to native
  • Property svn:keywords set to
    Id
    URL
    Date
    Rev
    Author
Line 
1"""
2SSL Middleware
3Antonio Cavedoni (cavedoni.com)
4
5$Id$
6$URL$
7
8Redirect selected paths to their HTTPS counterpart. HTTPS paths have to be
9in the settings file, through the HTTPS_PATHS tuple. All other URI paths
10will be assumed to be normal HTTP (and will be redirected back to their
11https-less counterpart if needed).
12"""
13__license__ = "Python"
14__copyright__ = "Copyright (C) 2006, Antonio Cavedoni"
15__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
16__contributors__ = [
17    "Stefano J. Attardi <http://attardi.org/>", 
18    "Carlo C8E Miron"
19    ]
20
21from django.conf import settings
22from django.http import HttpResponseRedirect
23from django.http import get_host
24
25class SSLMiddleware:
26    def process_request(self, request):
27        _to_redir = False
28        if hasattr(settings, "HTTPS_PATHS"):
29            for path in getattr(settings, "HTTPS_PATHS"):
30                if request.path.startswith("/%s" % path):
31                    if not request.is_secure():
32                        # Should be SSL but it isn't, redirect!
33                        return self._redirect(request, "https")
34                    else:
35                        return None
36                else:
37                    _to_redir = True
38            if _to_redir:
39                if request.is_secure():
40                    # Shouldn't be SSL but it is, redirect!
41                    return self._redirect(request, "http")
42
43    def _redirect(self, request, protocol):
44        newurl = "%s://%s%s" % \
45            (protocol, get_host(request), request.path)
46        if request.GET:
47            newurl += '?' + request.GET.urlencode()
48        if settings.DEBUG and request.method == 'POST':
49            raise RuntimeError, """
50Django can't redirect to the %(protocol)s URL you requested while maintaining
51POST data. Change your form to point to %(uri)s (dont't forget to specify the
52%(protocol)s) or remove the requested path from the HTTPS_PATHS tuple in the
53project settings""" % {'uri': newurl, 'protocol': protocol.upper()}
54        return HttpResponseRedirect(newurl)
Note: See TracBrowser for help on using the browser.