Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

authentication - django reathenticate middleware

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',
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...