0

I’m developing a django project and my veiws are function based and using django-allauth for authentication. Now, I’m searching for a pattern to work on all project so that any unauthenticated user is redirected automatically to login page. An alternative way is to add @login_required() decorator over every view function but I don’t see that as logical method.

1 Answers1

1

With the help of @Benbb96 I discovered that the solution is using a custom middleware. I did some researches because after Django 1.10 middlewares initialization have changed.

Here's my code

from django.http import HttpResponseRedirect
from django.urls import reverse

class AuthRequiredMiddleware:

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

    def __call__(self, request):
        redirect_url = reverse("account_login")

        if request.path == redirect_url:
            return self.get_response(request)
        if not request.user.is_authenticated:
            return HttpResponseRedirect(redirect_url)
        
        return self.get_response(request)

Added this to my settings.py

MIDDLEWARE = [
    ....
    'MyApp.middlewares.AuthRequiredMiddleware'
]

Also see https://docs.djangoproject.com/en/3.2/topics/http/middleware/#upgrading-middleware

Benbb96
  • 1,973
  • 1
  • 12
  • 21