Django - AuthenticationMiddleware setting request.user
NickName: Ask DateTime:2013-03-02T19:24:40

Django - AuthenticationMiddleware setting request.user


Regarding AuthenticationMiddleware, why did Django 1.3 handle the user property at class level, and why was it changed to an instance property in 1.4?


This is from 1.3

class LazyUser(object):
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_user'):
            from django.contrib.auth import get_user
            request._cached_user = get_user(request)
        return request._cached_user


class AuthenticationMiddleware(object):
    def process_request(self, request):
        request.__class__.user = LazyUser()
        return None


And this from 1.4

def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user


class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        request.user = SimpleLazyObject(lambda: get_user(request))
        # SimpleLazyObject inherits from LazyObject


In 1.3, I understood that process_request assigned LazyUser() to the class level user attribute, which to me basically means two things:

  • The HttpRequest class (request.__class__) stored its user attribute between two requests, so future request objects had access to it.
  • Whenever a view function tried to access request.user, the LazyUser object's __get__ method was triggered and returned a user object, either from the request's cache or from auth storage.

Am I correct about it?

Also, I have noticed in 1.4 these two major changes:

  • SimpleLazyObject is assigned to request, not to its class (so, it is an instance property).
  • LazyObject and SimpleLazyObject don't define (customize) their own __get__ method.

This way, when is get_user triggered?
How does AuthenticationMiddleware now store request.user between two requests, and override the statelessness of Http?

Copyright Notice:Content Author:「」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/15173907/django-authenticationmiddleware-setting-request-user

More about “Django - AuthenticationMiddleware setting request.user” related questions

Django - AuthenticationMiddleware setting request.user

Regarding AuthenticationMiddleware, why did Django 1.3 handle the user property at class level, and why was it changed to an instance property in 1.4? This is from 1.3 class LazyUser(object): ...

Show Detail

Django custom middleware request.user always AnonymousUser

I'm using Django 2.2 and DRF In my application, based on the user property, I need to change the request.user to a different user. class CustomMiddleware: def __init__(self, get_response): ...

Show Detail

add user_id attribute in AuthenticationMiddleware | Django

I have a following question regarding Django authentication middleware: class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'ses...

Show Detail

request.user returns None Django social-auth-app-django

I am a newbie in django social auth. I am using social-auth-app-django to authenticate Microsoft Azure AD user. Authentication process works well and user object is created inside the database. But

Show Detail

Django 3 Python 3.8 whitenoise not serving request.user

I get the error 'WSGIRequest' object has no attribute 'user' When writing: x.user = request.user x.save() In Django, I updated whitenoise to the latest version and I'm pretty sure that a post req...

Show Detail

Django 1.8 request.user is removed

I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request. These two are passed in the header of the request. The middlew...

Show Detail

What's the trick in Django's AuthenticationMiddleware

I'm reading the source code of Django and encountered a problem about AuthenticationMiddleware. As the documentation said AuthenticationMiddleware Adds the user attribute (a instance of User mo...

Show Detail

middleware updates request.user, but request.user becomes AnonymousUser in view

I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt returns a User object. # app.middlewares.py class JwtMiddleware: def __init__(self, get_response):

Show Detail

Help with Django RemoteUserMiddleware RemoteUserBackend with fresh database

The 1.3 release of Django includes the RemoteUserMiddleware and RemoteUserBackend classes to allow Apache to do authentication. See http://docs.djangoproject.com/en/dev/howto/auth-remote-user/ I h...

Show Detail

How to modify django's request.user in a Middleware?

What I'm trying to do is to detect the type of logged-in user and then setting a .profile parameter to request.user, so I can use it by calling request.user.profile in my views. To do this, I've wr...

Show Detail