What I want is redirect users to login page if they aren't authenticated. I made a middleware but the redirect is not working. Could someone give me a help?
My urls:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('contas/', include('django.contrib.auth.urls'), name='login'), # I want call this
path('', include('apps.props.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my middleware.py
from django.http import HttpResponseRedirect
from django.urls import reverse
class AuthRequiredMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse('login')) # Here I call login
response = self.get_response(request)
return response
and finally, my settings.py
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',
'middleware.AuthRequiredMiddleware', # Registering middleware
]
What I am getting is this page with "too many redirects"
My log:
Thans to @Melvyn and @Onsem comments I have improved my code. Here is one solution (We just need to be careful with files in media folder, they are accessed as AnonymousUser):
from django.http import HttpResponseRedirect
from django.urls import reverse
class AuthRequiredMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Here I call login if not authenticated and request is not login page
if not request.user.is_authenticated and request.path != reverse('login'):
return HttpResponseRedirect(reverse('login'))
response = self.get_response(request)
return response
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.