Skip to content

Instantly share code, notes, and snippets.

@eserge
Created February 27, 2012 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eserge/1926536 to your computer and use it in GitHub Desktop.
Save eserge/1926536 to your computer and use it in GitHub Desktop.
LoginMixin. A mixin for securing a class.
class LoginMixin(object):
"""Mixin for securing a class.
Taken from here:
https://groups.google.com/d/msg/django-users/g2E_6ZYN_R0/tnB9b262lcAJ
"""
def do_logout(self, request):
"""Logs the user out if necessary."""
logout(request)
return HttpResponseRedirect(self.get_login_url())
def get_test_func(self):
"""
Returns the function that is being used to test if a user is
authenticated.
"""
return get_test_func(getattr(self, 'test_func', None))
def get_login_url(self):
"""Returns the login URL."""
return getattr(self, 'login_url', None)
def get_redirect_field_name(self):
"""Returns the redirect_field_name."""
return getattr(self, 'redirect_field_name', None)
def dispatch(self, request, *args, **kwargs):
test_kwargs = {}
login_url = self.get_login_url()
if login_url:
test_kwargs['login_url'] = login_url
redirect_field_name = self.get_redirect_field_name()
if redirect_field_name:
test_kwargs['redirect_field_name'] = redirect_field_name
return user_passes_test(
self.get_test_func(),
**test_kwargs
)(super(LoginMixin, self).dispatch)(request, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment