Django

Django REST Framework Custom Authentication and Permissions

todoni 2021. 12. 30. 00:02

자 Django를 쓰는데 장고에서 제공하는 auth_user를 안 쓰고있다?

선택지는 두가지.

1. 울면서 모델과 프로젝트를 대폭 수정한다.

2. 어떻게든 원하는 대로 DRF를 활용하기.

나는 2번을 택했고.. 방법을 찾았다.

 

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

rest_framwork/permissions.py 의 내용이다.

나는 글 쓴 사람, 댓글 쓴 사람 등의 본인만 수정이나 삭제를 할 수 있게 하고싶다.

has_object_permission은 object 단위의 permission을 확인 해준다.

이 BasePermission 클래스를 상속 받아 내가 원하는 동작을 하게 overriding 할 것이다.

이렇게.

from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    본인만 수정할 수 있게 하는 권한.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True
        print('obj', obj.id)
        print('user', request.user)
        return obj.id == request.user.id

이제 

class RoutineViewSet(viewsets.ModelViewSet):
    queryset = Routine.objects.all()
    serializer_class = RoutineSerializer
    pagination_class = Pagination
    permission_classes = [IsOwnerOrReadOnly, ]
    filterset_fields = '__all__'

permission_classes를 내가 작성한 클래스로 지정해주고 

수정 요청을 보내면

안된다.

지금은 유저가 Anonymous 여서 id고 뭐고 없다. 프린트 해보면 None 찍힘.

방금 permission 클래스를 상속 받은 것 처럼 Authentication도 내가 직접 설정 해줘야

이 유저가 authorized 되었다 고 장고가 인식할 수 있고, 그래서 유저 정보도 받아올 수 있게 된다.

그건 어떻게 하냐면! 내일 쓸거임 ㅋ