ユーザー認証

8830 ワード

DRFに組み込まれている権限は次のとおりです.
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)

検査ヘッドCookie


custom default permissionsが必要です.
  • permissions.py
  • 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
  • has permissionメソッドオーバーフロー
    認証が完了したユーザーはTrueに戻り、
    未経験のプレイヤーであればreturn falseを行います.
  • 適用

    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)