Skip to content

Instantly share code, notes, and snippets.

@nobiki
Forked from ryanwitt/login_required_middleware.py
Last active March 28, 2017 17:16
Show Gist options
  • Save nobiki/7bc69dbc10f243611ca0d329ca31d263 to your computer and use it in GitHub Desktop.
Save nobiki/7bc69dbc10f243611ca0d329ca31d263 to your computer and use it in GitHub Desktop.
django 1.10
from django.http import HttpResponseRedirect
from django.conf import settings
# from django.views.decorators.clickjacking import xframe_options_exempt
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
self.process_request(request)
response = self.get_response(request)
response = self.process_response(request, response)
return response
## request
def process_request(self, request):
pass
## response
def process_response(self, request, response):
assert hasattr(request, 'user'), "user attribute not found."
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment