Issue
Hello Django community,
I want to send back the email and the id of the user alongside the token when the user authenticate. I guess I must change the UserLoginApiView class but I don't know how to override the ObtainAuthToken class to do that.
Does anybody have suggestions it would be very helpful?
class UserLoginApiView(ObtainAuthToken):
"""Handle creating user authentication tokens"""
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
This is my entire code on Github: https://github.com/KrestouferT/profiles-rest-api
Solution
In the docs it tell that you can override the return response of the post request in ObtainAuthToken:
If you need a customized version of the obtain_auth_token view, you can do so by subclassing the ObtainAuthToken view class, and using that in your url conf instead.
For example, you may return additional user information beyond the token value:
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
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,
'user_id': user.pk,
'email': user.email
})
And in your urls.py:
urlpatterns += [
url(r'^api-token-auth/', CustomAuthToken.as_view())
]
Answered By - Linh Nguyen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.