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를 띄어줄 수 없기 때문이다. 하단과 같은 에러문이 나오게 된다.

'Django > Django Rest Framework' 카테고리의 다른 글
| 20. Django DRF Q (0) | 2022.06.21 |
|---|---|
| 19. Django DRF orm 심화 (0) | 2022.06.20 |
| 17. Django DRF admin 페이지 심화 (0) | 2022.06.20 |
| 16. Django DRF permission_classes를 활용한 접근 권한 설정 (0) | 2022.06.19 |
| 15. Django DRF serializer (0) | 2022.06.19 |