danirus / django-comments-xtd

A pluggable Django comments application with thread support, follow-up notifications, mail confirmation, like/dislike flags, moderation, a ReactJS plugin and Bootstrap 5.3.
https://django-comments-xtd.readthedocs.io
BSD 2-Clause "Simplified" License
594 stars 158 forks source link

Issues with validation in WriteCommentSerializer #274

Closed dest81 closed 3 years ago

dest81 commented 3 years ago

I got errors: AttributeError: 'AnonymousUser' object has no attribute 'email' here AttributeError: 'AnonymousUser' object has no attribute 'get_full_name' here.

Check is done in wrong order. First should be checked user.is_anonymous and then user.get_full_name().

Also there are more possible issues with it. Not all user models inherited from AbstractUser and this means that 'email' and 'get_full_name' might not exist.

I can't test all cases but code below might work:

 from django.contrib.auth import get_user_model

    def validate_name(self, value):
        if not value.strip():
            if self.request.user.is_authenticated:
                if hasattr(self.request.user, "get_full_name"):
                    name = self.request.user.get_full_name()
                else:
                    name = self.request.user.get_username()
                if name:
                    return name

            raise serializers.ValidationError("This field is required")
        return value

    def validate_email(self, value):
        if not value:
            if self.request.user.is_authenticated:
                UserModel = get_user_model()
                email_field = UserModel.get_email_field_name()
                email = getattr(self.request.user, email_field, None)
                if email:
                    return email
            raise serializers.ValidationError("This field is required")
        return value
danirus commented 3 years ago

Hi @dest81, thanks for your report and your solution!

danirus commented 3 years ago

The code fix will be release with v2.8.3. Thanks again for reporting it.

dest81 commented 3 years ago

@danirus thank you for the quick reaction