0

I'm using DRF to allow users of my mobile app to authenticate to my web application.

I want to create a model instance associated with this user the first time a user "logs in" using the client.

I'm using token-based authentication in DRF, and for my /api/authenticate/ endpoint I'm pointing at url(r'^authenticate/', restviews.obtain_auth_token),

It seems like the best way to handle this is to override ObtainAuthToken(APIView), by adding this class to my api/views.py. This class looks like this:

class ObtainAuthTokenCustomized(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = AuthTokenSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key})


obtain_auth_token = ObtainAuthTokenCustomized.as_view()

It looks like I would want to insert a test prior to get_or_create for whether a token has been created previously for this user. And if so, perform the model instance creation I have planned.

Is this there a better way to handle this?

Rob
  • 1,656
  • 2
  • 17
  • 33

1 Answers1

0

From what I can tell this is the best place to handle this.

The reason is that DRF does not currently have a token expiration capability. So once a token is created with the above class it does not go away.

This means created will return True if it is the user's first time logging in:

token, created = Token.objects.get_or_create(user=user)

Thus you'd simply test created on the following line and perform the model creation or other actions necessary.

Additional logic may be necessary to handle a situation if tokens were removed. For example, if you used created an API logout method like the one given in this answer.

Community
  • 1
  • 1
Rob
  • 1,656
  • 2
  • 17
  • 33