nani
nani

Reputation: 203

Django validate AuthenToken Manually in a Serializer

So I have an app where I can book rooms. But I want to validate the user when he books a Room. I know that I can do that with the obtain_auth_token function. But I want to Validate the user myself with the token. So i am saving the token into the user when the user login to the site, and when the user want to book a room I'll give a token as a parameter to the booking view/serializer.

Now I want to validate this token send with the booking request.

Here is what my Serializer look like:

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

My View:

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()

and my Model:

class Buchung(models.Model):
TIME_CHOICES = (
    ('Ganztag', 'Ganztag'),
    ('Halbtags vor 14', 'Halbtags vor 14'),
    ('Halbtags nach 14', 'Halbtags nach 14'),
)


cearted_on = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(Mitarbeiter, on_delete=models.CASCADE, default='')
raum = models.ForeignKey(Raum, on_delete=models.CASCADE, default='')
platz = models.ForeignKey(Platz, on_delete=models.CASCADE, default='')
time_choices = models.CharField(max_length=100, choices=TIME_CHOICES, default='Ganztag')
datum = models.DateField(("Datum"), default=datetime.date.today)
token = models.CharField(max_length=300, default='')

def __str__(self):
    return "%s am %s" % (self.user, self.datum)

But I think the Problem is the Validator function in the Serializer is not working or not even being called. Thanks.

Upvotes: 1

Views: 461

Answers (1)

nani
nani

Reputation: 203

So I got the Problem.

The Problem was in the serializer, the validation function wasn't called at all. If this what I made is not safe, so pls call it out. So this is how my Serializer looks now.

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}}

Upvotes: 0

Related Questions