Manually checking django session id is currently authenticated

I need the function to tell me that the django session id is currently authenticated or not. I understand that this is already built into django, and it works fine for me.

But I have an external application that receives the session identifier, and when it passes the session identifier string back to django, I need to verify that this session identifier is valid and currently authenticated.

Where can I start reusing some of the built-in functions that django 1.2 has?

thanks

+4
source share
2 answers

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" 
+6
source

Here is the line in the source django.contrib.auth.__init__.login , which is registered by the user.

  request.session[SESSION_KEY] = user.id 

Logging out completely clears the session, so the presence of this key is an 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: it’s good if you are not using db sessions to extract the mechanism from the session.

+5
source

Source: https://habr.com/ru/post/1340189/


All Articles