0
votes

I have a few questions regarding tokens and username/pass pairs.

  1. I have a django rest API set up which uses tokens once a user has registered. However I do not know how to return the token to the user in a safe matter? Currently I use:

    response_data = UserSerializer(instance=new_user).data
    response_data['token'] = token.key
    return Response(response_data, status=status.HTTP_201_CREATED)
    

But in this way i can clearly see all of the details in my Response body in the browser? Even my password. How should I return it to the client ?

  1. When registering a User I do it this way:

    serialized = UserSerializer(data=request.DATA) if serialized.is_valid(): print(serialized.validated_data) new_user = get_user_model().objects.create(**serialized.validated_data) token = Token.objects.create(user=new_user)

Will this create my user properly ? Will the password be hashed?

Thank you

P.S. here is the whole method:

@api_view(['POST'])
def register_user(request):
    print (request)
    serialized = UserSerializer(data=request.DATA)
    if serialized.is_valid():
        print(serialized.validated_data)
        new_user = get_user_model().objects.create(**serialized.validated_data)
        token = Token.objects.create(user=new_user)

        response_data = UserSerializer(instance=new_user).data
        response_data['token'] = token.key
        return Response(response_data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
1

1 Answers

0
votes

I would handle #1 by setting a cookie, if that works for your use case. Relevant SO Post: How to set cookie in Django view and then render template.

For #2, I believe you should use create_user rather than create. Check the Django docs here. A quick way to check and see if your passwords are getting hashed properly is to pop open a shell, grab a user object, and see what the password looks like:

>>u = User.objects.get(id=1)
>>u.password
u'pbkdf2_sha256$12000$e30c2ea7a76f83b7c1a975ddc24286b675e714ebbbc72ccd5f0401730231ab57'

You will easily be able to tell whether or not the password has been hashed.