๋ทฐ๋ฅผ ์์ฑํ๊ธฐ์ ์์์ ์ ๊ทผ์ ์ ์ด๋ฅผ ์ํ ์ปค์คํ permissions๋ฅผ ์์ฑํ์.
permissions.py
๋จผ์ permissions.py๋ฅผ settings.py๊ฐ ์๋ ํด๋์ ์์ฑํ๋ค.
์ด ํด๋์ ์ปค์คํ permissions๋ฅผ ์์ฑํ ๊ฒ์ด๋ค.
import
permissions.py์ ์๋จ์ ๋ค์์ import ํด์ผ ํ๋ค.
from rest_framework import permissions
Permission ์์ฑ
์ด ์ธ๊ฐ์ง์ permission์ ์์ฑํ ๊ฒ์ด๋ค.
1. ๋ณธ์ธ์ ๋ฐ์ดํฐ๋ง ์ ๊ทผ๊ฐ๋ฅํ๊ฒ ํ๋ IsOwner
2. ๋ณธ์ธ๋ง ์์ ,์ญ์ ํ ์ ์๊ฒ ํ๋ ํ์ฉ๋ ํ๋ก์์๊ฒ๋ ์กฐํํ ์ ์๊ฒ ํ๋ IsOwnerOrReadOnly
3. ํ๋ก์ ์ ์ฒญ ์ ๋ณธ์ธ๊ณผ ํ๋ก์ ์ ์ฒญ์ ๊ด๋ จ๋ ์ฌ๋๋ง ์กฐํ,ํธ์งํ ์ ์๊ฒ ํ๋ IsFollowerOrOwner
IsOwner
๋ฐ์ดํฐ์ ์์ ์๋ง ์ ๊ทผํ๊ณ ์์ ์ญ์ ํ ์ ์๊ฒ ํ๋ค
class IsOwner(permissions.BasePermission):
"""
๋ณธ์ธ์ data๋ง ์ ๊ทผ ๊ฐ๋ฅํ๋ค.
"""
def has_permission(self, request, view):
return request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return obj.user == request.user
IsOwnerOrReadOnly
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
๊ฐ์ฒด๋ฅผ ๋ง๋ ์ฌ์ฉ์๋ง ์์ ํ ์ ์๋ค.
"""
def has_permission(self, request, view):
return request.user.is_authenticated
def has_object_permission(self, request, view, obj):
# ์์ฒญํ ์ฌ์ฉ์๊ฐ ํด๋น ๊ฐ์ฒด์ ์์ ์์ธ ๊ฒฝ์ฐ์๋ง ์ฐ๊ธฐ ๊ถํ์ ๋ถ์ฌํจ
return obj.follower == request.user or obj.following_user == request.user
IsFollowerOrOwner
class IsFollowerOrOwner(permissions.BasePermission):
"""
Custom permission to allow reading followed items only if they are open.
"""
def has_permission(self, request, view):
return request.user.is_authenticated
def has_object_permission(self, request, view, obj):
# Check if the request method is safe (GET, HEAD, OPTIONS)
if request.method in permissions.SAFE_METHODS:
if Follow.objects.filter(follower=request.user, following_user=obj.user, status='accepted').exists() | Follow.objects.filter(follower=obj.user, following_user=request.user, status='accepted').exists():
return obj.is_open
return obj.user == request.user