Login

User from session key

Author:
jdunck
Posted:
January 5, 2009
Language:
Python
Version:
1.0
Tags:
session user auth
Score:
3 (after 5 ratings)

This blog post outlined how to get the user from the session key: http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/

Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing.

>>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396'
>>> user_from_session_key(skey)
<User: jeremyd>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def user_from_session_key(session_key):
    from django.conf import settings
    from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
    from django.contrib.auth.models import AnonymousUser

    session_engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
    session_wrapper = session_engine.SessionStore(session_key)
    user_id = session_wrapper.get(SESSION_KEY)
    auth_backend = load_backend(session_wrapper.get(BACKEND_SESSION_KEY))

    if user_id and auth_backend:
      return auth_backend.get_user(user_id)
    else:
      return AnonymousUser()

More like this

  1. MoinMoin auth backend by yourcelf 4 years, 11 months ago
  2. Case Insensitive Authentication Backend by ericflo 6 years, 5 months ago
  3. Support for permissions for anonymous users in django ModelBackend by jb 3 years, 9 months ago
  4. Custom requests auth class for Tastypie API key authentication by jezdez 3 years, 5 months ago
  5. OracleAuthBackend by nosrednakram 6 years ago

Comments

blueklein76 (on October 13, 2010):

This snippet didn't work for me (under Django 1.2). Here's a modified version that seems to do the trick:

def user_from_session_key(session_key):
    from django.conf import settings
    from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
    from django.contrib.auth.models import AnonymousUser

    session_engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
    session_wrapper = session_engine.SessionStore(session_key)
    session = session_wrapper.load()
    user_id = session.get(SESSION_KEY)
    backend_id = session.get(BACKEND_SESSION_KEY)
    if user_id and backend_id:
        auth_backend = load_backend(backend_id)
        user = auth_backend.get_user(user_id)
        if user:
            return user
    return AnonymousUser()

#

Please login first before commenting.