Home > Blockchain >  How do I return a 401 response in a SimpleJWT Custom Token when using the Django Rest Framework?
How do I return a 401 response in a SimpleJWT Custom Token when using the Django Rest Framework?

Time:07-10

I would like to return a 401 message if the user is not enabled. When I try returning a response instead of a token it doesn't work which I understand to be because the serializer is expecting the token. How do I customise it to send a 401 response if the user is not enabled please?

My custom token class is as below:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from rest_framework.response import Response

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        if user.is_enabled:
            token = super().get_token(user)
            # Add custom claims
            token['name'] = user.name
            token['gender'] = user.gender

            return token
        else:
            return Response({'detail':'Account not enabled'}, status=status.HTTP_401_UNAUTHORIZED)

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

The URL root looks like:

re_path(r'^authenticate/',CustomTokenObtainPairView.as_view(), name='authenticate'),

CodePudding user response:

You can return some symbol like None in Python from get_token if the user is not enabled and then override the get method of CustomTokenObtainPairView to return 401 if the value of get_token is None.

CodePudding user response:

You can make something like that

from rest_framework import status, serializers
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework_simplejwt.tokens import RefreshToken


class LoginUserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True, min_length=5)


class LoginUserApi(APIView):

    def post(self, request):
        serializer = LoginUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = authenticate(email=request.data['email'], password=request.data['password'])
        if not user:
            return Response({'detail':'Incorrect email or password'}, status=status.HTTP_400_BAD_REQUEST)
        elif not user.is_enabled:
            return Response({'detail':'Account not enabled'}, status=status.HTTP_401_UNAUTHORIZED)

        # Generate Token
        refresh = RefreshToken.for_user(user)
        data = {}
        data['name'], data['gender'] = user.name, user.gender
        data['refresh'], data['access'] = str(refresh), str(refresh.access_token)    

        return Response(data, status=status.HTTP_200_OK)

Reference from docs

  • Related