Source code for api.posts.permissions
from typing import Any, List
from django.views import View
from rest_framework import permissions
from rest_framework.request import Request
from common.utils.permissions import get_nested_attr
from services.posts.comment_image import CommentImageService
[docs]
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
All users can read.
"""
owner_attributes: List[str] = [
"author",
"post.author",
]
[docs]
def has_object_permission(self, request: Request, view: View, obj: Any) -> bool:
# Read permissions are allowed for any request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed for the owner of the object.
# Check if object has any of the defined owner attributes and if the value matches request.user
return any(get_nested_attr(obj, attr) == request.user for attr in self.owner_attributes)