from rest_framework import permissions from .utils import get_current_wechat_user class IsAuthorOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow authors of an object to edit it. Assumes the model instance has an `author` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the author of the object. # We need to manually get the user because we are using custom auth logic (get_current_wechat_user) # instead of request.user for some reason (or in addition to). # However, DRF's request.user might not be set if we don't use a standard authentication class. # Based on views.py, it uses `get_current_wechat_user(request)`. current_user = get_current_wechat_user(request) return current_user and obj.author == current_user