35 lines
1.1 KiB
Python
35 lines
1.1 KiB
Python
from django.shortcuts import redirect
|
|
from django.urls import reverse
|
|
from django.conf import settings
|
|
|
|
class LoginRequiredMiddleware:
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
def __call__(self, request):
|
|
if not request.user.is_authenticated:
|
|
path = request.path_info
|
|
|
|
# Allow access to login, logout, admin, and any other exempted paths
|
|
# We use try/except in case URLs are not defined yet
|
|
try:
|
|
login_url = reverse('login')
|
|
logout_url = reverse('logout')
|
|
except:
|
|
login_url = '/accounts/login/'
|
|
logout_url = '/accounts/logout/'
|
|
|
|
exempt_urls = [
|
|
login_url,
|
|
logout_url,
|
|
'/admin/',
|
|
]
|
|
|
|
# Check if path starts with any of the exempt URLs
|
|
is_exempt = any(path.startswith(url) for url in exempt_urls)
|
|
|
|
if not is_exempt:
|
|
return redirect(f"{login_url}?next={path}")
|
|
|
|
response = self.get_response(request)
|
|
return response |