본문 바로가기
Django/Django Rest Framework

18. Django DRF permission_classes/admin, 사용자 별 권한 설정

by S.T.Lee 2022. 6. 20.
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import APIException
from rest_framework import status

class GenericAPIException(APIException):
    def __init__(self, status_code, detail=None, code=None):
        self.status_code=status_code
        super().__init__(detail=detail, code=code)

class IsAdminOrIsAuthenticatedReadOnly(BasePermission):
    """
    admin 사용자는 모두 가능, 로그인 사용자는 조회만 가능
    """
    SAFE_METHODS = ('GET', )
    message = '접근 권한이 없습니다.'

    def has_permission(self, request, view):
        user = request.user

        if not user.is_authenticated:
            response ={
                    "detail": "서비스를 이용하기 위해 로그인 해주세요.",
                }
            raise GenericAPIException(status_code=status.HTTP_401_UNAUTHORIZED, detail=response)

        if user.is_authenticated and user.is_admin:
            return True
            
        if user.is_authenticated and request.method in self.SAFE_METHODS:
            return True
        
        return False

SAFE_METHODS에 권한을 줄 방식을 써주면 된다.

if not user.is_authenticated를 해주는 이유는 로그인 되지 않은 유저한테는 message를 띄어줄 수 없기 때문이다. 하단과 같은 에러문이 나오게 된다.