"""
SSL Middleware
Antonio Cavedoni (cavedoni.com)

$Id$
$URL$

Redirect selected paths to their HTTPS counterpart. HTTPS paths have to be
in the settings file, through the HTTPS_PATHS tuple. All other URI paths 
will be assumed to be normal HTTP (and will be redirected back to their 
https-less counterpart if needed).
"""
__license__ = "Python"
__copyright__ = "Copyright (C) 2006, Antonio Cavedoni"
__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
__contributors__ = [
    "Stefano J. Attardi <http://attardi.org/>", 
    "Carlo C8E Miron"
    ]

from django.conf import settings
from django.http import HttpResponseRedirect
from django.http import get_host

class SSLMiddleware:
    def process_request(self, request):
        _to_redir = False
        if hasattr(settings, "HTTPS_PATHS"):
            for path in getattr(settings, "HTTPS_PATHS"):
                if request.path.startswith("/%s" % path):
                    if not request.is_secure():
                        # Should be SSL but it isn't, redirect!
                        return self._redirect(request, "https")
                    else:
                        return None
                else:
                    _to_redir = True
            if _to_redir:
                if request.is_secure():
                    # Shouldn't be SSL but it is, redirect!
                    return self._redirect(request, "http")

    def _redirect(self, request, protocol):
        newurl = "%s://%s%s" % \
            (protocol, get_host(request), request.path)
        if request.GET:
            newurl += '?' + request.GET.urlencode()
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, """
Django can't redirect to the %(protocol)s URL you requested while maintaining 
POST data. Change your form to point to %(uri)s (dont't forget to specify the 
%(protocol)s) or remove the requested path from the HTTPS_PATHS tuple in the 
project settings""" % {'uri': newurl, 'protocol': protocol.upper()}
        return HttpResponseRedirect(newurl)
