DRF에서 기본 제공하는 permissions는 아래와 같다.
from rest_framework.permissions import IsAuthenticated
class ExampleView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
default permissions를 커스텀 해야했다.
from django.contrib.auth import get_user_model
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
from rest_framework.views import APIView
from .helper_funcs import jwt_decode, ClientInfo
class HasToken(BasePermission):
def has_permission(self, request, view):
# 봇 여부 판단
client_info = ClientInfo(request)
if client_info.is_bot():
return False
# 쿠키 여부 판단 시작
if "access_token" not in request.COOKIES:
return False
token = request.COOKIES["access_token"]
# 유저 확인
user_id = jwt_decode("JWT " + token)
if not user_id:
return False
user = get_user_model().objects.get(id=user_id)
request.user = user
# 유저 검증 완료
return True
request.user = user
from core.management.permissions import HasToken
(그 외의 import 부분 생략)
class CartAPIView(APIView):
"""장바구니 C, R, D"""
permission_classes = [HasToken]
def get(self, request):
user = request.user
cart_qs = Cart.objects.filter(user=user, is_deleted=False)
if not cart_qs:
msg = {"MESSAGE": "empty cart"}
return Response(msg, status=status.HTTP_204_NO_CONTENT)
carted_products = Product.objects.filter(cart__in=cart_qs)
serializer = CartListSerializer(carted_products, many=True)
return Response(serializer.data)