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