Permissions
π object level permissions
βκ°μ²΄ μμ€μ νκ°(κΆν)β λ DRFμ generic viewκ° get_object()
λ©μλλ₯Ό νΈμΆν λ μ€νλλ€.
βview μμ€μ νκ°(κΆν)β κ³Ό λ§μ°¬κ°μ§λ‘ ν΄λΉ κ°μ²΄μ λν μμ μ μ§νν μ μμ κ²½μ°μλ
exceptions.PermissionDenied μμΈκ° λ°μνλ€.
λ§μΌ λ΄κ° μμ±νλ viewμμ βκ°μ²΄ μμ€μ κΆνβμ κ°ννκ³ μΆκ±°λ, genric viewμμ
get_object
λ₯Ό μ¬μ μνκ³ μΆλ€λ©΄, κΌ .check_object_permissions(request, obj)
λ©μλλ₯Ό
κΌ μμ±ν΄μ€μΌ νλ€.
# views.py
def get_object(self,pk):
post = get_object_or_404(self.queryset, pk=pk)
self.check_object_permissions(self.request, post)
return post
π permissions 컀μ€ν νκΈ°
rest_framework/permissions.py λ‘ κ°λ³΄λ©΄ λ€μκ³Ό κ°μ΄ μ μλμ΄ μλ€.
class BasePermission(metaclass=BasePermissionMetaclass):
"""
A base class from which all permission classes should inherit.
"""
def has_permission(self, request, view):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
def has_object_permission(self, request, view, obj):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
has_permission
λ©μλμ κ²½μ°μλ λͺ¨λ HTTP μμ²μ μ¬μ©κ°λ₯νλ€
POST, GET, PUT, DELETE
λ°λ©΄μ has_object_permissions
λ©μλμ κ²½μ°μλ get_object
λ©μλλ‘ λΆν°
νΈμΆμ΄ λκΈ° λλ¬Έμ, GET, PUT, DELETE μλ§ μ¬μ©ν μ μλ€.
from rest_framework.permissions import BasePermission
class CustomObjectPermission(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.user == request.user