Django在Serializer中手动验证AuthenToken

时间:2018-06-11 12:07:44

标签: python django validation django-rest-framework django-serializer

所以我有一个可以预订房间的应用程序。但我想在预订房间时验证用户。我知道我可以使用obtain_auth_token函数来做到这一点。但我想用令牌自己验证用户。 因此,当用户登录网站时,我将令牌保存到用户中,当用户想要预订房间时,我会将令牌作为参数提供给预订视图/序列化程序。

现在我想用预订请求验证此令牌发送。

以下是我的Serializer的样子:

[future] = client.scatter([[1, 2, 3]], ...)

我的观点:

class BuchungSerializer(ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
token = serializers.CharField(required=True, allow_blank=False, write_only=True)
class Meta:
    """Meta class to map serializer's fields with the model fields."""
    model = Buchung
    fields = ['id', 'user', 'time_choices', 'raum', 'platz', 'datum', 'token']
    related_fields = ['user', 'raum', 'platz']
    extra_kwargs = {"token": {"write_only": True}}


    username = serializers.CharField(source='user.username')

    def validate_token(self, value):
        user = Mitarbeiter.objects.filter(Q(username = username))
        if user.exists() and user.count() == 1:
            user_obj = user.first()
            user_token = user_obj.usertoken
            token = Token.objects.get(key=value)
            if token == user_token:
                return value
            else:
                raise ValidationError("Token not Valid")
        else:
            raise ValidationError("User doesn't exist")


    def create(self, validated_data):
        reservation = Buchung(
            user=validated_data['user'],
            time_choices=validated_data['time_choices'],
            raum=validated_data['raum'],
            platz=validated_data['platz'],
            datum=validated_data['datum'],
        )
        reservation.set_token(validated_data['token'])
        reservation.save()
        return reservation

和我的模特:

class CreateBuchungView(generics.ListCreateAPIView):
queryset = Buchung.objects.all()
serializer_class = BuchungSerializer
#permission_classes = [IsAuthenticated]


def perform_create(self, serializer):
    """Save the post data when creating a new reservation."""
    serializer.save()

但我认为问题是Serializer中的Validator功能无法工作或甚至不被调用。 感谢。

1 个答案:

答案 0 :(得分:0)

所以我遇到了问题。

问题在于序列化程序,验证功能根本没有被调用。如果这个我做的不安全,那么请把它叫出来。 所以这就是我的Serializer现在的样子。

class BuchungSerializer(ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
def validate(self, data):
    username = data.get("username")
    user = Mitarbeiter.objects.filter(Q(username = username))
    if user.exists() and user.count() == 1:
        user_obj = user.first()
        input_token = data.get("token")
        token = Token.objects.get(user=user_obj)
        yay_token = token.key
        if yay_token == input_token:
            return data
        else:
            raise ValidationError("UToken not Valid")
    else:
        raise ValidationError("User doesn't exist")

class Meta:
    """Meta class to map serializer's fields with the model fields."""
    model = Buchung
    fields = ['id', 'user', 'username', 'time_choices', 'raum', 'platz', 'datum', 'token']
    related_fields = ['user', 'raum', 'platz']
    extra_kwargs = {"token": {"write_only": True}}