| 1 | """ |
|---|
| 2 | SSL Middleware |
|---|
| 3 | Antonio Cavedoni (cavedoni.com) |
|---|
| 4 | |
|---|
| 5 | $Id$ |
|---|
| 6 | $URL$ |
|---|
| 7 | |
|---|
| 8 | Redirect selected paths to their HTTPS counterpart. HTTPS paths have to be |
|---|
| 9 | in the settings file, through the HTTPS_PATHS tuple. All other URI paths |
|---|
| 10 | will be assumed to be normal HTTP (and will be redirected back to their |
|---|
| 11 | https-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 | |
|---|
| 21 | from django.conf import settings |
|---|
| 22 | from django.http import HttpResponseRedirect |
|---|
| 23 | from django.http import get_host |
|---|
| 24 | |
|---|
| 25 | class 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, """ |
|---|
| 50 | Django can't redirect to the %(protocol)s URL you requested while maintaining |
|---|
| 51 | POST 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 |
|---|
| 53 | project settings""" % {'uri': newurl, 'protocol': protocol.upper()} |
|---|
| 54 | return HttpResponseRedirect(newurl) |
|---|