Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: HTTPS for just login page?

Tags:

ssl

django

I just added this SSL middleware to my site http://www.djangosnippets.org/snippets/85/ which I used to secure only my login page so that passwords aren't sent in clear-text. Of course, when the user navigates away from that page he's suddenly logged out. I understand why this happens, but is there a way to pass the cookie over to HTTP so that users can stay logged in?

If not, is there an easy way I can use HTTPS for the login page (and maybe the registration page), and then have it stay on HTTPS if the user is logged in, but switch back to HTTP if the user doesn't log in?

There are a lot of pages that are visible to both logged in users and not, so I can't just designate certain pages as HTTP or HTTPS.

like image 498
mpen Avatar asked May 09 '10 22:05

mpen


2 Answers

Actually, modifying the middleware like so seems to work pretty well:

class SSLRedirect:
        
    def process_view(self, request, view_func, view_args, view_kwargs):
        if 'SSL' in view_kwargs:
            secure = view_kwargs['SSL']
            del view_kwargs['SSL']
        else:
            secure = False
                
        if request.user.is_authenticated():
            secure = True
    
        if not secure == self._is_secure(request):
            return self._redirect(request, secure)
    
    def _is_secure(self, request):
        if request.is_secure():
            return True
    
        #Handle the Webfaction case until this gets resolved in the request.is_secure()
        if 'HTTP_X_FORWARDED_SSL' in request.META:
            return request.META['HTTP_X_FORWARDED_SSL'] == 'on'
    
        return False
    
    def _redirect(self, request, secure):
        protocol = secure and "https://secure" or "http://www"
        newurl = "%s.%s%s" % (protocol,settings.DOMAIN,request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
        """Django can't perform a SSL redirect while maintaining POST data.
           Please structure your views so that redirects only occur during GETs."""
    
        return HttpResponsePermanentRedirect(newurl)
like image 103
mpen Avatar answered Nov 19 '22 10:11

mpen


Better is to secure everything. Half secure seems secure, but is totally not. To put it blank: by doing so you are deceiving your end users by giving them a false sense of security.

So either don't use ssl or better: use it all the way. The overhead for both server and end user is negligible.

like image 1
Wim Feijen Avatar answered Nov 19 '22 11:11

Wim Feijen