add user_id attribute in AuthenticationMiddleware | Django
NickName:Aleksei Khatkevich Ask DateTime:2020-10-29T18:01:51

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, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(request))

As you can see here middleware calls method get_user from backend (in my case simple_jwt) and puts this method in a SimpleLazyObject in order to evaluate later.

def get_user(self, validated_token):
    """
    Attempts to find and return a user using the given validated token.
    """
    try:
        user_id = validated_token[api_settings.USER_ID_CLAIM]
    except KeyError:
        raise InvalidToken(_('Token contained no recognizable user identification'))

    try:
        user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
    except User.DoesNotExist:
        raise AuthenticationFailed(_('User not found'), code='user_not_found')

    if not user.is_active:
        raise AuthenticationFailed(_('User is inactive'), code='user_inactive')

    return user

What I want to do is to keep request.user = SimpleLazyObject(lambda: get_user(request)) in order to provide user instance for apps that uses it but for my custom apps I want to add something like

pseudocode

request.user_id = user_id from  user (user_id = validated_token[api_settings.USER_ID_CLAIM])

in order to not query database each and every request for user object in case I need only user_id which I already have directly in get_user method in backend.

Question – how to pass user_id from get_user() to AuthenticationMiddleware.process_request() and set request.user_id attribute to request without evaluating SimpleLazyObject?

Strangelly i can't assign attributes to request in class JWTAuthentication(authentication.BaseAuthentication): where get_user() is belong

Thank you.

Internal Server Error: /auth/users/me/
Traceback (most recent call last):
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\asgiref\sync.py", line 330, in thread_handler
    raise exc_info[1]
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\django\core\handlers\exception.py", line 38, in inner
    response = await get_response(request)
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\django\utils\deprecation.py", line 126, in __acall__
    response = await sync_to_async(
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\asgiref\sync.py", line 296, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\asyncio\tasks.py", line 440, in wait_for
    return await fut
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\asgiref\current_thread_executor.py", line 23, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\asgiref\sync.py", line 334, in thread_handler
    return func(*args, **kwargs)
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\django\contrib\auth\middleware.py", line 26, in process_request
    request.user_id = _get_user_session_key(request)
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\django\contrib\auth\__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "C:\ProgramData\Miniconda3\envs\entropy\lib\site-packages\django\contrib\sessions\backends\base.py", line 65, in __getitem__
    return self._session[key]
KeyError: '_auth_user_id'

Copyright Notice:Content Author:「Aleksei Khatkevich」,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/64588820/add-user-id-attribute-in-authenticationmiddleware-django

More about “add user_id attribute in AuthenticationMiddleware | Django” related questions

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

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

HttpRequest instance add attribute dynamically in Django?

I'm confused with HttpRequest object in Django. I know that the AuthenticationMiddleware will add a user to request which is an instance of HttpRequest. And the code is here, but what I want to sho...

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

Django: why is _cached_user an instance attribute of request while LazyUser is a class attribute of request?

In Django: def get_user(request): from django.contrib.auth.models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY]

Show Detail

How to add an attribute to Django request object

I try to add the business attribute to the request object by using my own middleware, it nicely works with rest_framework.authentication.SessionAuthentication and I can use request.business in my v...

Show Detail

How to add samesite none option in django settings file

I used Django 2.0.2 version. I tried to process google authentication in Django project. I got the token but I will pass URL and token. it return 404 error. I need to add samesite='none' in Django

Show Detail

Django 'settings' object has no attribute

this is my first python project. I am having issues setting up a project someone else has written. I am getting the following 'Settings' object has no attribute 'FOXYCART_URL' here's the stack trac...

Show Detail

django session store has not attribute

django 1.5 I have a eclipse windows development setup and a Linux Apache host. I have to pull some user data from a WSDL. When I do this from eclipse it works like a charm but when I update the...

Show Detail

Django : 'WSGIRequest' object has no attribute 'user'? - AuthenticationMiddleware & SessionAuthenticationMiddleware are in sequence

Getting the following error while try to access the django admin panel. Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.9.8 Python Version: 2.7.10

Show Detail