Changeset 40

Show
Ignore:
Timestamp:
10/05/06 20:12:00 (2 years ago)
Author:
verbosus
Message:

Added sslmiddleware

Files:
1 copied

Legend:

Unmodified
Added
Removed
  • django/trunk/middleware/sslmiddleware.py

    r8 r40  
    11""" 
    2 URL Middleware 
    3 Stefano J. Attardi (attardi.org) 
     2SSL Middleware 
     3Antonio Cavedoni (cavedoni.com) 
    44 
    55$Id$ 
    66$URL$ 
    77 
    8 Cleans up urls by adding/removing trailing slashes, adding/removing 
    9 the www. prefix, and allowing the language to be set from the url. 
    10  
    11 If APPEND_SLASH is set to False, trailing slashes are removed from the 
    12 urls, except for urls which have an explicit trailing slash in 
    13 urls.py, in which case a trailing slash is added. 
    14  
    15 If REMOVE_WWW is set to True, the www. prefix is removed. 
    16  
    17 Finally, ?lang=xx can be appended to any url to override the default 
    18 language setting. This override is remembered for the following 
    19 requests. For example, /article?lang=it would show the article in 
    20 Italian regardless of brower settings or cookies, and any following 
    21 request to the site would be shown in Italian by default. 
    22  
    23 Changelog 
    24  
    25 1.3 
    26 Only use sessions for the language preference if the session 
    27 cookie has already been set (regardless of whether session middleware 
    28 is active). Otherwise use the plain django_language cookie. 
    29 Only import the FlatPages module if it is active. 
    30  
    31 1.2 
    32 Added support for FlatPages. 
    33 Switched to Django's resolve function (with workaround for when it 
    34 returns None). 
    35  
    36 1.1 
    37 Various bugfixes. 
    38  
    39 1.0 
    40 First release. 
     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). 
    4112""" 
    42 __version__ = "1.3" 
     13__version__ = "1.0" 
    4314__license__ = "Python" 
    44 __copyright__ = "Copyright (C) 2006, Stefano J. Attardi" 
    45 __author__ = "Stefano J. Attardi <http://attardi.org/>" 
    46 __contributors__ = ["Antonio Cavedoni <http://cavedoni.com/>"] 
     15__copyright__ = "Copyright (C) 2006, Antonio Cavedoni" 
     16__author__ = "Antonio Cavedoni <http://cavedoni.com/>" 
     17__contributors__ = ["Stefano J. Attardi <http://attardi.org/>"] 
    4718 
    4819from django.conf import settings 
    4920from django.http import HttpResponseRedirect, Http404 
    5021from django.core.urlresolvers import resolve 
    51 from django.utils.translation import check_for_language 
    52 import os 
    5322 
    54 class UrlMiddleware: 
     23class SSLMiddleware: 
     24    def process_request(self, request): 
     25        if hasattr(settings, "HTTPS_PATHS"): 
     26            for path in getattr(settings, "HTTPS_PATHS"): 
     27                if request.path.startswith("/%s" % path) and not \ 
     28                        request.path.is_secure(): 
     29                    # Redirect to https:// 
     30                    self._redirect(request, "https") 
    5531 
    56     def process_request(self, request): 
    57  
    58         # Change the language setting for the current page 
    59         if "lang" in request.GET and check_for_language(request.GET["lang"]): 
    60             if hasattr(request, 'session'): 
    61                 request.session['django_language'] = request.GET["lang"] 
    62             else: 
    63                 request.COOKIES['django_language'] = request.GET["lang"] 
    64  
    65         # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW 
    66         old_url = [request.META['HTTP_HOST'], request.path] 
    67         new_url = old_url[:] 
    68  
    69         # if REMOVE_WWW is True, remove the www. from the urls if necessary 
    70         if hasattr(settings, "REMOVE_WWW") and settings.REMOVE_WWW and old_url[0].startswith('www.'): 
    71             new_url[0] = old_url[0][4:] 
    72  
    73         if hasattr(settings, "APPEND_SLASH") and not settings.APPEND_SLASH: 
    74             # if the url is not found, try with(out) the trailing slash 
    75             if not self._urlExists(old_url[1]): 
    76  
    77                 if old_url[1][-1] == "/": 
    78                     other = old_url[1][:-1] 
    79                 else: 
    80                     other = old_url[1] + "/" 
    81  
    82                 if self._urlExists(other): 
    83                     new_url[1] = other 
    84  
    85             if new_url != old_url: 
    86                 # Redirect 
    87                 newurl = "%s://%s%s" % (os.environ.get('HTTPS') == 'on' and 'https' or 'http', new_url[0], new_url[1]) 
    88                 if request.GET: 
    89                     newurl += '?' + request.GET.urlencode() 
    90                 return HttpResponseRedirect(newurl) 
     32            if request.path.is_secure(): 
     33                # Redirect to http:// 
     34                self._redirect(request, "http") 
    9135 
    9236        return None 
    9337 
    94     def process_response(self, request, response): 
    95  
    96         # Change the language setting for future pages 
    97         if "lang" in request.GET and check_for_language(request.GET["lang"]): 
    98             if 'sessionid' in request.COOKIES: 
    99                 request.session['django_language'] = request.GET["lang"] 
    100             else: 
    101                 response.set_cookie('django_language', request.GET["lang"]) 
    102  
    103         return response 
    104  
    105     def _urlExists(self, path): 
    106         try: 
    107             if resolve(path) is None: raise Http404 # None?!? You mean 404... 
    108             return True 
    109         except Http404: 
    110             # check for flatpages 
    111             if "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware" in settings.MIDDLEWARE_CLASSES: 
    112                 from django.contrib.flatpages.models import FlatPage 
    113                 return FlatPage.objects.filter(url=path, sites__id=settings.SITE_ID).count() == 1 
     38    def _redirect(self, request, protocol): 
     39        newurl = "%s://%s/%s/" % \ 
     40            (protocol, request.META['HTTP_HOST'], request.path) 
     41        if request.GET: 
     42            newurl += '?' + request.GET.urlencode() 
     43        return HttpResponseRedirect(newurl) 
     44