One of my company's project is in Django and I was assigned to a task to 'add authentication to the top-level router' so we don't forget to add an authentication code to every view, such as:
if not request.user.is_authenticated:
return HttpResponseRedirect('/admin/login/?next=/admin/some-page/')
After doing a bit of research I found out that this can be accomplished by writing my own middleware. I was not familiar at all with the concept until doing my homework. So now I am trying to write a LoginRequiredMiddleware
class that intercepts every request and sends the user to the login page if not authenticated and, after authentication, to the original page the user was trying to access.
This is the code I have so far.
middleware.py
from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import is_safe_url
import re
EXEMPT_URLS = [re.compile(settings.LOGIN_REDIRECT_URL.lstrip('/'))] # '/admin'
class LoginRequiredMiddleware(MiddlewareMixin):
def process_request(self, request):
assert hasattr(request, 'user'), "The Login Required Middleware"
if not request.user.is_authenticated:
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
redirect_to = settings.LOGIN_REDIRECT_URL
if len(path) > 0 and is_safe_url(
url=request.path_info, allowed_hosts=request.get_host()):
redirect_to = f"{settings.LOGIN_REDIRECT_URL}/login?next={request.path_info}"
return HttpResponseRedirect(redirect_to)
I have already registered the middleware in the MIDDLEWARE
list in settings.py
and included both SessionMiddleware
and AuthenticationMiddleware
but I have not managed to get it to work. I can access a page that requires authentication in incognito mode, for example, without logging in.
I would like some tips on what am I doing wrong or which better path I should be following.