Created
May 23, 2020 18:56
-
-
Save bencleary/901a0874d3e1820d4f3ef7ab6b83ef5b to your computer and use it in GitHub Desktop.
Login Required middleware as per the upcoming Django implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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