Search code examples
javascriptdjangoreact-nativedjango-rest-frameworkdjango-rest-framework-jwt

DFR simple jwt get authToken from a user instance instead of username/password


I have a simple chat app, authentication in it works exaclty as whatsapp

Get phone number => if doesn't exist create one else skip => send validation code and set it as "phone_code" field in User model => finally remove the "phone_code" if validated

The app is built in React Native with Rest framework as the API, I'm new to this and I'm struggling to get the authentication token without the password. i use djangorestframework-simplejwt

my register view:

@api_view(('POST',))
def register(request):
    if request.method == 'POST':
        serializer = UserSerializer(data=request.data)
        if not serializer.is_valid():
            if 'is not valid' in serializer.errors['phone_number'][0]:
                return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
        phone_number = serializer.initial_data['phone_number'].replace(' ', '')
        try:
            user = User.objects.get(phone_number=phone_number)
        except User.DoesNotExist:
            user = User.objects.create_user(
                phone_number=phone_number, username=phone_number)
        user.phone_code = randint(99999, 999999)
        user.save()
        TokenObtainPairView()
        return Response(serializer.data, status.HTTP_200_OK)
        # todo send validation code, I will handle later

my Login view (Chich validates for the validation code)

@api_view(['POST',])
def loginuser(request):
    if request.method == 'POST':
        phone_number = request.data.get('phone_number')
        try:
            user = User.objects.get(phone_number=phone_number)
            if int(request.data.get('phone_code')) == user.phone_code and user.phone_code:
                user.phone_code = None
                user.save()
                #!!!!!!!!!!!!!!!!!!!NOW HOW CAN I GET THE JWT AUTHENTICATION TOKEN AND SEND IT TO MY REACT NATIVE APP?!
                return JsonResponse({'phone_number': phone_number}, status=200)

            else:
                return JsonResponse({'error': "Invalid code"}, status=400)
        except Exception as error:
                return JsonResponse({'error': error}, status=500)

when the user validates his phonenumber, how can I send the jwt format auth token with the Response?

urls.py:

path('api/token/', users_views.ObtainToken.as_view(), name='token_obtain_pair'),

my Custom obtainToken view:

class ObtainToken(TokenObtainPairView):
    permission_classes = (AllowAny,)
    serializer_class = MyTokenObtainPairSerializer

Also I found out that when I was using Postman if I send an empty password the system will give a the authentication token. I would appreciate any help, thanks


Solution

  • You should base your code on the existing views and serialiazer from rest_framework_simplejwt : using TokenObtainPairView is a good start, keep that.

    Then in your seriliazer_class, MyTokenObtainPairSerializer, you should use TokenObtainSerializer

    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
        def validate(self, attrs):
            self.user = User.objects.get(phone_number=phone_number)
            # Do the verification with the phone_code here, if error, return a response with an error status code
    
            refresh = self.get_token(self.user)
    
            data['refresh'] = text_type(refresh)
            data['access'] = text_type(refresh.access_token)
    
            return data