You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from rest_framework import permissions
  2. class IsOwnerOrReadOnly(permissions.IsAuthenticatedOrReadOnly):
  3. """
  4. Object-level permission to only allow owners of an object to edit it.
  5. Assumes the model instance has an `owner` attribute.
  6. """
  7. def __init__(self, owner_field_name="owner"):
  8. self.__owner_field_name = owner_field_name
  9. def __call__(self):
  10. return self
  11. def has_object_permission(self, request, view, obj):
  12. # Read permissions are allowed to any request,
  13. # so we'll always allow GET, HEAD or OPTIONS requests.
  14. if request.method in permissions.SAFE_METHODS:
  15. return True
  16. return getattr(obj, self.__owner_field_name) == request.user
  17. class OwnerOnly(permissions.IsAuthenticatedOrReadOnly):
  18. def has_permission(self, request, view):
  19. return request.user.is_authenticated()
  20. def has_object_permission(self, request, view, obj):
  21. return obj.owner == request.user
  22. class SuperUserOnly(permissions.BasePermission):
  23. """
  24. The request is authenticated as a user, or is a read-only request.
  25. """
  26. def has_permission(self, request, view):
  27. return request.user.is_superuser
  28. def has_object_permission(self, request, view, obj):
  29. return request.user.is_superuser