0

I have the following requirements:

  1. Users must be able to see (and log out) their other sessions.
  2. Sessions must expire BOTH at browser close and after a perioid of inactivity.
  3. default database can not be used to store sessions.

My current approach would be to set SESSION_EXPIRE_AT_BROWSER_CLOSE and add a middleware class that checks the last_activity / and updates the timestamp (or calls logout() if the session has expired) and also run a periodic cleanup on inactive sessions.

However, I couldn't find a way to access the non-database backed sessions outside a request (- or a way to access anything except the current session inside a request) Furthermore, I couldn't find any documentation how to store the django_session table to another database.

I'm currently using cache backed sessions using a file based cache, but that can be changed - the only requirement is not to store the sessions in the default database.

Community
  • 1
  • 1
Kimvais
  • 38,306
  • 16
  • 108
  • 142

1 Answers1

1

1) For this to find all sessions of current user - request.user - you will have to iterate through all session objects decode data and check the user id. Not very optimized. Something like:

May be you can optimize to iterate over non-expired sessions.

for s in Session.objects.all():
    data = s.get_decoded()
    if data['_auth_user_id'] == request.user.id:
        # you got session for current user

2) For this you need to manipulate session expiry data in custom middleware as you described.

3) To store session in different DB, you need to add database router.

Something like :

class SessionRouter(object):
    """
    A router to control all database operations 
    sessions.
    """
    def db_for_read(self, model, **hints):

        if model == Session or model == SessionStore
            return 'session_db'
        return None
        #similar more methods

And in settings

DATABASES = {
    'session_db': {
        #settings for session db
    },
    #any other databases.
Rohan
  • 52,392
  • 12
  • 90
  • 87
  • It seems that writing something that does what I need and use that instead of sessions seems like the most viable option - `~/git/django/django/contrib/sessions $ find . -name '*.py' |xargs cat|wc -l` says `1600` ... – Kimvais Sep 26 '13 at 06:44
  • @Kimvais, you can write your own middleware. But I think for #1 you need to do that in some view, based on user action. – Rohan Sep 26 '13 at 06:53