Skip to content

Instantly share code, notes, and snippets.

@bencleary
Created May 20, 2020 19:41
Show Gist options
  • Save bencleary/04c512aa8e1ce7239bc225903ee3221e to your computer and use it in GitHub Desktop.
Save bencleary/04c512aa8e1ce7239bc225903ee3221e to your computer and use it in GitHub Desktop.
from django.http import HttpResponseRedirect
from django.conf import settings
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# checks if the user is not already logged in
if not request.user.is_authenticated:
# checks that the requested URL is not in the excluded URL list
if not any(request.path_info == url for url in settings.LOGIN_EXEMPT_URLS):
# redirect to login page and pass the desired url as next
# on sign in the user will be redirected to their desired url
redirect_url = f"{settings.LOGIN_URL}?next={request.path_info}"
return HttpResponseRedirect(redirect_url)
else:
# continue with response
response = self.get_response(request)
return response
else:
# continue with response
response = self.get_response(request)
return response
# Add this to your settings.py
# update with whatever URL's you want to be public
LOGIN_EXEMPT_URLS = ['/', '/api/news/']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment