Manually validate a django session id is currently authenticated

5.9k views Asked by At

I need to have a function tell me if a Django session-id is currently authenticated or not. I understand this is already built into Django and I have that working just fine.

But I have an external app that gets passed a session id, and when it passes the session-id string back to Django I need to validate that this session id is valid and currently authenticated.

Where do I start reusing some of the built-in functions Django 1.2 has?

2

There are 2 answers

1
Reto Aebersold On BEST ANSWER

You can do it like this (not tested, but it shows you a possible way):

from django.utils.importlib import import_module
from django.conf import settings
from django.contrib.auth import get_user
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend

engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore(YOUR_SESSION_KEY)

try:
    user_id = session[SESSION_KEY]
    backend_path = session[BACKEND_SESSION_KEY]
    backend = load_backend(backend_path)
    user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
    user = AnonymousUser()

if user.is_authenticated():
    print "User"
else:
    print "Guest"
1
Yuji 'Tomita' Tomita On

Here's a line in the source django.contrib.auth.__init__.login that logs in a user.

    request.session[SESSION_KEY] = user.id

Logging out flushes the session completely, therefore the presence of that key is the authenticated user.

from django.contrib.auth import SESSION_KEY
from django.contrib.sessions.models import Session
try:
    session = Session.objects.get(session_key=my_key)
    session.get_decoded()[SESSION_KEY]
    return (True, "Authenticated")
except (Session.DoesNotExist, KeyError):
    return (False, "Not authenticated")

PS: nice one by aeby to pull from session engine if you're not using db sessions.