0

I'm using a custom middleware that looks like this:

class DisallowLoggedInUsers:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        print("in interceptor before response")
        print("user: ", request.user)
        print("is_authenticated?: ", request.user.is_authenticated)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        print("in interceptor after response")
        print("user: ", request.user)
        print("is_authenticated?: ", request.user.is_authenticated)

        return response

I also have similar logs inside the get method of the view. Here's the log output:

in interceptor before response
user: AnonymousUser
is_authenticated? False

in view
user: John Doe/john@test.domain
is_authenticated?  True

in interceptor after response
user: John Doe/john@test.domain
is_authenticated?  True

Here is my order of middlewares:

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'userdata.customInterceptor.DisallowLoggedInUsers',
]

Even though I've put my custom middleware way down the order (below AuthenticationMiddleware, the request.user object is not set untill the view is processed. I even tried trapping the request at process_view of the middleware but got an AnonymousUser there still.

What am I doing wrong?

I'm on Django 3.1.7 and djangorestframework 3.12.3.

Note: I checked this related question, but it did not help.

Aldo
  • 707
  • 7
  • 15

0 Answers0