Skip to content

Instantly share code, notes, and snippets.

@brunobbbs
Forked from robgolding/login_required.py
Last active August 29, 2015 14:16
Show Gist options
  • Save brunobbbs/7f890cd10f03a329148b to your computer and use it in GitHub Desktop.
Save brunobbbs/7f890cd10f03a329148b to your computer and use it in GitHub Desktop.
class LoginRequiredMixin(object):
"""
View mixin which requires that the user is authenticated.
"""
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(
self, request, *args, **kwargs)
class PermissionsRequiredMixin(object):
"""
View mixin which verifies that the logged in user has the specified
permissions.
Settings:
`required_permissions` - list/tuple of required permissions
Example Usage:
class SomeView(PermissionsRequiredMixin, ListView):
...
required_permissions = (
'app1.permission_a',
'app2.permission_b',
)
...
"""
required_permissions = ()
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.has_perms(self.required_permissions):
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(PermissionsRequiredMixin, self).dispatch(
request, *args, **kwargs)
class StaffRequiredMixin(object):
"""
View mixin which requires that the authenticated user is a staff member
(i.e. `is_staff` is True).
"""
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
class SuperUserRequiredMixin(object):
"""
View mixin which requires that the authenticated user is a super user
(i.e. `is_superuser` is True).
"""
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_superuser:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(SuperUserRequiredMixin, self).dispatch(request,
*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment