当使用django-rest-framework创建用户时,返回authtoken响应

时间:2015-09-06 21:40:22

标签: python django rest

我正在使用django-rest-framework(http://www.django-rest-framework.org)构建API。

我使用内置的authtoken进行用户身份验证。

这是我的问题:虽然我知道我可以通过向方法token_views.obtain_auth_token发送包含有效用户名/密码凭据的POST来获取token.key,但我希望在注册后将有效的令牌密钥返回给客户端

我目前的解决方案并不安全,根本不可取。这是代码: 串行器:

class UserSerializer(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields=('email', 'password', 'id', 'token') #by having the token as a 
    #field, a get request returns a list of everyone AND their tokens!!!! no-bueno!

        write_only_fields = ('password',)
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined')

    def get_token(self, validated_data):
        #where we populate the 'token' field above
        user = User.objects.filter(email=validated_data.email)
        token = Token.objects.get(user=user)
        return token.key

    def create(self, validated_data):
        """
        Create and return a new User instance, given the validated data.
        """
        password = validated_data.pop('password', None)
        email = validated_data.pop('email', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        if email is not None:
            instance.username = email.lower()
            instance.email = email.lower()
        instance.save()
        # Retrieves token associated with user (works)
        token = Token.objects.get(user=instance)
        # would like to send token back to client in json response

        return instance

长话短说,我只想在成功创建用户对象后在响应中返回一个标记值。在此先感谢!!

0 个答案:

没有答案