0

I'm working on a Django site hosted on an Apache server with mod_wsgi. The site is only on https as we have Apache redirect any http requests to https.

The project I'm working on is called Skittle. I have a custom user model called SkittleUser which inherits from AbstractBaseUser and is set as the AUTH_USER_MODEL in our settings.py file.

os.environ['HTTPS'] = "on" is set in the wsgi.py file.

SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True are both set in settings.py

The issue that we are having right now is that logging in as a user is unreliable. When you go to the login page, some times it works while other times it doesn't. Then while browsing the site, you will suddenly lose your session and be kicked down to an anonymous user.

We are currently running our test site here if anybody wants to take a look: https://skittle.newlinetechnicalinnovations.com/discover/
Our production site is at www.dnaskittle.com but does not yet incorporate user logins as the feature doesn't work.

A test user: email: [email protected] password: asdf

If the login does not work, you will see in the top right "Welcome, Login" in which case, just try clicking on Login again and use the same credentials. It may take 5-6 times of doing that process before you will actually get logged in.

You will know it works when you see "Welcome Tester, Logout, My Genomes"

After you are logged in, it may stick for a while, but browsing around to other pages will eventually kick you back off. There is no consistent amount of pages that you can go through before this happens, and it doesn't happen on any specific page.

Any insights on this would be greatly appreciated.

Also of note, going to the Django admin page (which is not our code, but base django code) has the same issue.

1
  • Just a note, when you do finally get signed in... after navigating through a few pages when you get kicked, it looks like in the database a new session is created for you. And you are logged in as an anonymous user. Jul 16, 2013 at 22:21

3 Answers 3

0

I've gotten this issue sorted out now. Users can not login while on HTTPS using while using the listed setup.

What I did:

In settings.py add:

SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_NAME = 'DNASkittle'

I also wiped the current django_sessions database in case that was causing issues with old lingering data.

I did not setup extra middleware or SSLRedirect, and everything is working all ship shape.

1
  • I had exactly the same issue. Unfortunately, applying this solution does not work for me. Could you please explain the rationale why this should help?
    – schacki
    Jun 4, 2014 at 10:04
0

It's little longer and complex the SSL system. to handle the session/login properly with https you can set a configuration with the session_cookies.

settings.py:

ENABLE_SSL=False #in the debug mode in the production passed it to True
MIDDLEWARE_CLASSES = (
    'commerce.SSLMiddleware.SSLRedirect', #)
# the session here is to use in your views when a user is connected
SESSION_COKIE_NAME='sessionid'
#the module to store sessions data
SESSION_ENGINE='django.contrib.sessions.backends.db'    
#age of cookie in seconds (default: 2 weeks)
SESSION_COOKIE_AGE=7776000 # the number of seconds in 90 days
#whether a user's session cookie expires when the web browser is closed
SESSION_EXPIRE_AT_BROWSER_CLOSE=False
#whether the session cookie should be secure (https:// only)
SESSION_COOKIE_SECURE=False    

SSLMiddleware is a file you going to define in your project like.

SSLMiddleware.py:

from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect

SSL='SSL'

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 not secure == self._is_secure(request):
        return self._redirect(request,secure)

def _is_secure(self,request):
   if request.is_secure():
       return True
   if 'HTTP_X_FORWARD_SSL' in request.META:
       return request.META['HTTP_X_FORWARD_SSL'] == 'on'
   return False

def _redirect(self,request,secure):
    protocol = secure and "https" or "http"
    newurl ="%s://%s%s" % (protocol, request, request.get_full_path())
    if settings.DEBUG and request.method=="POST":
        raise RuntimeError, \
    return HttpResponsePermanentRedirect(newurl)

Now in your urls which should handle your logins or connection add the line

urls.py:

from project import settings
urlpatterns += patterns('django.contrib.auth.views',
    (r'^login/$','login',{'template_name':'registration/login.html','SSL':settings.ENABLE_SSL},'login'),

Try to adapt this to your code. and don't forget to turn ENABLE_SSL to True

3
  • I added the couple of items in the settings.py that I was missing. ENABLE_SSL, the cookie name, session engine. I didn't see a need for the SSLRedirect as everything is already forwarded to https via apache. But still, I can log into the site once, then will randomly get kicked off a few navigations later. Jul 16, 2013 at 22:18
  • ok, the need for the SSLRedirect is to secure user password transfer when logged in, if it really important for you it should be secure. now you have to set the cookies in setting and use them in you login views if you want to get connected for a period define by your shelf or your organization. use the cookies in your views.py to handle the connection. it should works.
    – drabo2005
    Jul 17, 2013 at 3:40
  • Thank you for the input, this did get us going down the right direction. Jul 25, 2013 at 17:45
0

For users login with HTTPS, you have to enable SSL and use code that matches your case to use it. For the user session you can use this:

First check if you have in settings.py:

INSTALLED_APPS= ('django.contrib.sessions',)

and use the request.sessions in your file.py:

request.session['id']='the_id_to_store_in_browser' or 'other_thing'

Here you use request.session like a special SessionStore class which is similar to python dictionary.

In your views.py for example before rendering a template or redirecting test the cookie with the code:

if : 
 # whatever you want
  if request.session.test_cookie_worked():
    request.session.delete_test_cookie()
  return HttpResponseRedirect(up-to-you)
else:
 # whatever you want
 request.session.set_test_cookie()
return what-you-want

with this code, the user session will stick a wide, depending on your SESSION_COOKIE_AGE period.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.