Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access request.session from backend.get_user

first of all: this is not the same as this. The ModelBackend has no request member.

I want to access the session of the current user without access to the global request object or his/her session ID.

Why? I wrote my own authentication backend, extending ModelBackend. In that I have the function get_user (self, user_id), that gets called with every request (this is done automatically by the Django auth middleware). Unfortunately, get_user doesn't have access to request, but nonetheless in my case I want to check with data in the session (Why again? Because I don't have a local database and get all data from a remote middleware. The session would be a comfortable way to do some kind of caching).

like image 400
Boldewyn Avatar asked Jul 07 '09 10:07

Boldewyn


2 Answers

You can use the tiny ThreadLocalMiddleware. It makes the request object everywhere available.

from django_tools.middlewares import ThreadLocal

request = ThreadLocal.get_current_request()
# request.session <-- is now available

Do not forget to add the middleware into the MIDDLEWARE_CLASSES tuple of your settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'django_tools.middlewares.ThreadLocal.ThreadLocalMiddleware',
    ...
)
like image 132
Jeremi Avatar answered Oct 19 '22 00:10

Jeremi


The RemoteUserBackend (from django.contrib.auth.backends) uses special middleware, RemoteUserMiddleware, to access request data. Maybe you could do it this way, too.

like image 35
drdaeman Avatar answered Oct 19 '22 01:10

drdaeman