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?