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?
Advertisement
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"