jpadilla / django-rest-framework-jwt

JSON Web Token Authentication support for Django REST Framework
http://jpadilla.github.io/django-rest-framework-jwt/
MIT License
3.19k stars 652 forks source link

How can I add user data to the Response on login? #307

Closed JadSayegh closed 7 years ago

JadSayegh commented 7 years ago

I'm trying to add information from the user model to the Response that is returns when a user logs-in with their username and password. Right now the rest_framework_jwt.views.obtain_jwt_token only returns the token. I've considered subclassing ObtainJSONWebToken, in an effort to add the user data by overriding the post method. Is this the recommended approach?

JadSayegh commented 7 years ago

My subclass currently looks like this and is working fine. Is this a correct approach?

from rest_framework_jwt import views as jwt_views
from .serializers import UserSerializer 

class UserLoginViewJWT(jwt_views.ObtainJSONWebToken):
    user_serializer_class = UserSerializer

    def post(self, request, *args, **kwargs):
        response =  super().post(request, *args, **kwargs)

        if response.status_code == status.HTTP_200_OK:
            user = get_user_model().objects.get(email=request.data[get_user_model().USERNAME_FIELD])
            serialized_user = self.user_serializer_class(user)
            response.data.update(serialized_user.data)
        return response
jpadilla commented 7 years ago

You can also do this with the JWT_RESPONSE_PAYLOAD_HANDLER setting. http://getblimp.github.io/django-rest-framework-jwt/#jwt_response_payload_handler