Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

as a relative noob to django I have been creating a users app.

I would like a logged in superuser to have to reauthenticate if they access the admin area having used the rest of the app.

I am trying this custom middleware that I have written. Is there a django integrated solution to this problem already, and are there any issues that you can see with my code?

from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth import logout
import re


class ReauthenticateMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.pages = []
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_superuser:
            match = re.match(r'/admin/', request.path)
            if len(self.pages) and self.pages[-1] is not None and match is not None:
                referred = re.match(r'/admin/', self.pages[-1])
                if referred is None and match is not None:
                    messages.add_message(request, messages.INFO, 'You must reauthenticate')
                    logout(request)
                    self.pages = []
                    return redirect('/admin/login/')
        
            if request.path[-1] == '/':
                self.pages.append(request.path)
    
        response = self.get_response(request)


        # Code to be executed for each request/response after
        # the view is called.

        return response

I have the custom middleware on the python path and have added it to settings as follows:

MIDDLEWARE = [
    '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',
    'ReauthenticateMiddleware.ReauthenticateMiddleware',
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...