[Django]-How to get logged in user's uid from session in Django?

19đź‘Ť

âś…

There is a django.contrib.auth.models.User object attached to the request; you can access it in a view via request.user. You must have the auth middleware installed, though.

👤mipadi

79đź‘Ť

In case anyone wants to actually extract a user ID from an actual Session object (for whatever reason – I did!), here’s how:

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
session_data = session.get_decoded()
print session_data
uid = session_data.get('_auth_user_id')
user = User.objects.get(id=uid)

Credit should go to Scott Barnham

👤hwjp

8đź‘Ť

This:

def view(request):
    if request.user.is_authenticated:
         user = request.user
         print(user)
         # do something with user
👤diegueus9

2đź‘Ť

An even easier way to do this is to install django-extensions and run the management command print_user_for_session.

And this is how they do it:

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

👤boatcoder

0đź‘Ť

In case hwjp solution doesn’t work for you (“Data is corrupted”), here is another solution:

import base64
import hashlib
import hmac
import json

def session_utoken(msg, secret_key, class_name='SessionStore'):
    key_salt = "django.contrib.sessions" + class_name
    sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
    utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
    return utoken


def decode(session_data, secret_key, class_name='SessionStore'):
    encoded_data = base64.b64decode(session_data)
    utoken, pickled = encoded_data.split(b':', 1)
    expected_utoken = session_utoken(pickled, secret_key, class_name)
    if utoken.decode() != expected_utoken:
        raise BaseException('Session data corrupted "%s" != "%s"',
                            utoken.decode(),
                            expected_utoken)
    return json.loads(pickled.decode('utf-8'))

s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))

credit to: http://joelinoff.com/blog/?p=920

👤Rani

0đź‘Ť

You can use this code

from django.contrib.sessions.models import Session
from importlib import import_module
from  django.contrib.auth.middleware import get_user
from django.http import HttpRequest


engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
session = SessionStore(sessionid)
request = HttpRequest()
request.session = session
user = get_user(request) 
👤Sarath Ak

Leave a comment