Skip to content

Instantly share code, notes, and snippets.

@LouisdeBruijn
Created March 15, 2020 09:42
Show Gist options
  • Select an option

  • Save LouisdeBruijn/e044dbf95cdcecc15501e6d8be316755 to your computer and use it in GitHub Desktop.

Select an option

Save LouisdeBruijn/e044dbf95cdcecc15501e6d8be316755 to your computer and use it in GitHub Desktop.
def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login', message=default_message):
"""
Decorator for views that checks that the user is logged in and is a
superuser, displaying message if provided.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_superuser and u.is_authenticated,
login_url=login_url,
redirect_field_name=redirect_field_name,
message=message
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def staff_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login', message=default_message):
"""
Decorator for views that checks that the user is logged in and is
staff, displaying message if provided.
"""
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_staff and u.is_authenticated,
login_url=login_url,
redirect_field_name=redirect_field_name,
message=message
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
def unauthenticated_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, home_url='/', message=unauthenticated_message):
"""
Decorator for views that checks that the user is
not logged in, displaying message if provided.
"""
actual_decorator = user_passes_test(
lambda u: not u.is_active and not u.is_authenticated,
login_url=home_url,
redirect_field_name=redirect_field_name,
message=message
)
if view_func:
return actual_decorator(view_func)
return actual_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment