Skip to content

Instantly share code, notes, and snippets.

@bencleary
Created May 23, 2020 18:56
Show Gist options
  • Save bencleary/901a0874d3e1820d4f3ef7ab6b83ef5b to your computer and use it in GitHub Desktop.
Save bencleary/901a0874d3e1820d4f3ef7ab6b83ef5b to your computer and use it in GitHub Desktop.
Login Required middleware as per the upcoming Django implementation
from functools import wraps
def login_not_required(view_func):
def wrapped(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped.login_required = False
return wraps(view_func)(wrapped)
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.auth.views import redirect_to_login
class LoginRequiredMiddleware(AuthenticationMiddleware):
def process_view(self, request, view_func, view_args, view_kwargs):
if request.user.is_authenticated:
return None
view_class = getattr(view_func, 'view_class', None)
if view_class and not getattr(view_func, 'login_required', True):
return None
if not getattr(view_func, 'login_required', True):
return None
return redirect_to_login(request.get_full_path())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment