I found online that we are able to override JSONWebTokenSerializer by having this in our url
url(r'^login/', ObtainJSONWebToken.as_view(serializer_class=CustomJWTSerializer)),
and in view I have
class CustomJWTSerializer(JSONWebTokenSerializer):
def __init__(self, *args, **kwargs):
super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)
self.fields['email'] = serializers.CharField()
self.fields['password'] = PasswordField(write_only=True)
def validate(self, attrs):
credentials = {
'username': attrs.get('email'),
'password': attrs.get('password')
}
print(credentials)
if all(credentials.values()):
user = authenticate(**credentials)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
payload = jwt_payload_handler(user)
return {
'token': jwt_encode_handler(payload),
'user': user
}
else:
msg = _('Unable to login with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "{username_field}" and "password".')
msg = msg.format(username_field=self.username_field)
raise serializers.ValidationError(msg)
With this, I can start overriding the original but somehow the return object is always just the token.
Somehow I couldn't find where it's being generated, it does look like it's because of
return {
'token': jwt_encode_handler(payload),
'user': user
}
Even with this, user is not returned just the tokens.
I even tried taking out the whole return and have return{} but with the right credential, it still returns something like {"token": null}
I even tried using return Response({}) but still where is it getting the {"token": null} from and why is it not showing my user object as response though? I used print (user) and for sure it exists that it's valid though
You can use additional setting - JWT_RESPONSE_PAYLOAD_HANDLER - to return key and user in json response. See documentation http://getblimp.github.io/django-rest-framework-jwt/, there is an example of using JWT_RESPONSE_PAYLOAD_HANDLER.
It's my code example:
settings.py
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER': 'back.views.jwt_response_payload_handler',
}
in back/view.py
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username')
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With