This commit is contained in:
jeremygan2021
2026-02-12 15:51:18 +08:00
parent e69a24b555
commit 4ac8767659
14 changed files with 2851 additions and 141 deletions

View File

@@ -0,0 +1,23 @@
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