Created
May 23, 2020 19:17
-
-
Save bencleary/9bbeefb0b8b2cc84e85797696c41b6a3 to your computer and use it in GitHub Desktop.
A simple example of a decorator to restrict by group in Django
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.decorators import user_passes_test | |
from django.core.exceptions import PermissionDenied | |
def restrict_access_to_groups(groups: list, raise_exception: bool = False): | |
""" | |
Decorator for views that requires the user to be part of a group, | |
if they are not the user is not allowed into the page. | |
If the raise_exception parameter is given the PermissionDenied exception | |
is raised returning a 403 status code | |
""" | |
def in_groups(user): | |
# checks if the user is authenticated, if not returns False | |
if not user.is_authenticated: | |
return False | |
# checks if the user is a superuser or is part of the given groups | |
if user.groups.filter(name__in=groups).exists() | user.is_superuser: | |
return True | |
# if raise_exception is given raise the 403 error | |
if raise_exception: | |
raise PermissionDenied | |
# return False otherwise | |
return False | |
return user_passes_test(in_groups) |
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.shortcuts import HttpResponse | |
from django.views import View | |
from django.utils.decorators import method_decorator | |
from myapp.decorators import * | |
@method_decorator(restrict_access_to_groups(["admin", "sales"], True), name="dispatch") | |
class HelloWorldView(View): | |
def get(self, request): | |
return HttpResponse("Hello World!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment