Boldewyn
Boldewyn

Reputation: 82724

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).

Upvotes: 13

Views: 6490

Answers (3)

drdaeman
drdaeman

Reputation: 11471

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

Upvotes: 4

littlegreen
littlegreen

Reputation: 7420

You can also pass a 'request' parameter to the authenticate function any time you call it:

def authenticate(self, request, **kwargs):
    ....

Upvotes: 0

Jeremi
Jeremi

Reputation: 111

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',
    ...
)

Upvotes: 6

Related Questions