Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

56 lignes
1.6 KiB

  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 OwnerOnlyIfPrivate(permissions.BasePermission):
  18. def __init__(self, owner_field_name="owner"):
  19. self.__owner_field_name = owner_field_name
  20. def __call__(self):
  21. return self
  22. def has_object_permission(self, request, view, obj):
  23. if getattr(obj, "private"):
  24. return request.user == getattr(obj, self.__owner_field_name)
  25. return True
  26. class OwnerOnly(permissions.IsAuthenticatedOrReadOnly):
  27. def has_permission(self, request, view):
  28. return request.user.is_authenticated()
  29. def has_object_permission(self, request, view, obj):
  30. return obj.owner == request.user
  31. class SuperUserOnly(permissions.BasePermission):
  32. """
  33. The request is authenticated as a user, or is a read-only request.
  34. """
  35. def has_permission(self, request, view):
  36. return request.user.is_superuser
  37. def has_object_permission(self, request, view, obj):
  38. return request.user.is_superuser