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):
JavaScript
x
22
22
1
from django.utils.importlib import import_module
2
from django.conf import settings
3
from django.contrib.auth import get_user
4
from django.contrib.auth.models import AnonymousUser
5
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend
6
7
engine = import_module(settings.SESSION_ENGINE)
8
session = engine.SessionStore(YOUR_SESSION_KEY)
9
10
try:
11
user_id = session[SESSION_KEY]
12
backend_path = session[BACKEND_SESSION_KEY]
13
backend = load_backend(backend_path)
14
user = backend.get_user(user_id) or AnonymousUser()
15
except KeyError:
16
user = AnonymousUser()
17
18
if user.is_authenticated():
19
print "User"
20
else:
21
print "Guest"
22