PageRenderTime 94ms CodeModel.GetById 85ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/django/middleware/ssl.py

https://code.google.com/p/mango-py/
Python | 59 lines | 43 code | 12 blank | 4 comment | 21 complexity | 126229fd086e0212f8b01c3945298d5d MD5 | raw file
 1# -*- coding: utf-8 -*-
 2__license__ = "Python"
 3__copyright__ = "Copyright (C) 2007, Stephen Zabel"
 4__author__ = "Stephen Zabel - sjzabel@gmail.com"
 5__contributors__ = "Jay Parlar - parlar@gmail.com"
 6
 7from django.conf import settings
 8from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, get_host
 9
10SSL = 'SSL'
11
12class SSLRedirect:
13    def process_request(self, request):
14        ssl_force = getattr(settings, 'SSL_FORCE', None)
15        if settings.SSL_ENABLED and ssl_force:
16            if not self._is_secure(request):
17                return self._redirect(request, True)
18        return None
19
20    def process_view(self, request, view_func, view_args, view_kwargs):
21        if SSL in view_kwargs:
22            secure = view_kwargs[SSL]
23            del view_kwargs[SSL]
24        else:
25            # none means I don't care if its secure or not, just let the request through
26            return None
27        
28        if (not secure == self._is_secure(request)) and settings.SSL_ENABLED:
29            return self._redirect(request, secure)
30
31    def _is_secure(self, request):
32        if request.is_secure():
33            return True
34
35        #Handle the Webfaction case until this gets resolved in the request.is_secure()
36        if 'HTTP_X_FORWARDED_SSL' in request.META:
37            return request.META['HTTP_X_FORWARDED_SSL'] == 'on'
38
39        return False
40
41    def _redirect(self, request, secure):
42        protocol = secure and "https" or "http"
43        host = get_host(request)
44        
45        # if we are being proxied use the default behavoir. Thus proxied servers will only work if outside the proxy they look like they are on standard ports.
46        if 'HTTP_X_FORWARDED_HOST' not in request.META:
47            if hasattr(settings,'HTTP_REDIRECT_TO_HTTPS'):
48                host = settings.HTTP_REDIRECT_TO_HTTPS
49            
50            if hasattr(settings,'HTTP_REDIRECT_TO_HTTPS_PORT'):
51                host = host.split(":")[0] + ":" + str(settings.HTTP_REDIRECT_TO_HTTPS_PORT)
52        
53        newurl = "%s://%s%s" % (protocol,host,request.get_full_path())
54        if settings.DEBUG and request.method == 'POST':
55            raise RuntimeError, \
56        """Django can't perform a SSL redirect while maintaining POST data.
57           Please structure your views so that redirects only occur during GETs."""
58
59        return HttpResponsePermanentRedirect(newurl)