public
Created

Login Required Decorator

  • Download Gist
mixins.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from django.conf import settings
from django.http import HttpResponseRedirect
 
class LoginRequired(object):
def dispatch(self, request, *args, **kwargs):
if self.check_logged_in(request.user):
return super(LoginRequired, self).dispatch(request, *args, **kwargs)
else:
return self.not_logged_in(self):
 
def check_logged_in(self, user):
return user.is_authenticated()
 
def not_logged_in(self):
return HttpResponseRedirect(settings.LOGIN_URL)
views.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## No Special Behavior, just Login Required
 
class ProtectedView(LoginRequired, TemplateView):
template_name = "secret.html"
 
## Check to make sure the user is active and logged in
 
class ProtectedView(LoginRequired, TemplateView):
template_name = "secret.html"
 
def check_logged_in(self, user):
return super(ProtectedView, self).check_logged_in(user) and user.is_active
 
## Check Logged in, and return a 403
 
class ProtectedView(LoginRequired, TemplateView):
template_name = "secret.html"
 
def not_logged_in(self):
return HttpResponseForbidden()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.