12

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

Community
  • 1
  • 1
Boldewyn
  • 81,211
  • 44
  • 156
  • 212

3 Answers3

6

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',
    ...
)
Jeremi
  • 111
  • 2
  • 4
4

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

drdaeman
  • 11,159
  • 7
  • 59
  • 104
  • Sorry, I know this is an old thread but I am looking at the referenced code and I don't see where it is accessing the request data for the user I just authenticated. – ThatAintWorking Jun 12 '14 at 17:48
  • 2
    @RonSmith I've updated the links a bit. The trick is that everything's done by `RemoteUserMiddleware.process_request` - it gets passed a `request` object (middleware.py#L40). It checks for presence of `Remote-User` HTTP header (L50) and if so passes that data to `RemoteUserBackend.authenticate` (L73) and saves the result in `request` (L77). In this case, only value of HTTP header is passeb, but the idea was that if you need session info in auth backend, you could preemptively stash it there from a middleware. – drdaeman Jun 12 '14 at 19:04
  • 2
    Do you mind update your answer with few lines of code as an example? Thanks. – Paul Lo Dec 18 '14 at 06:57
0

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

def authenticate(self, request, **kwargs):
    ....
littlegreen
  • 7,290
  • 9
  • 45
  • 51