Exemplo n.º 1
0
class TranslationFeedbackSecureSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100, required=False, allow_blank=True)
    whats_wrong = serializers.CharField(max_length=1000, required=False, allow_blank=True)
    suggestion = serializers.CharField(max_length=1000, required=False, allow_blank=True)
    translation_id = serializers.IntegerField(required=True)

    recaptcha = ReCaptchaV2Field()

    def validate(self, attrs):
        if not attrs.get('whats_wrong', '').strip() and not attrs.get('suggestion', '').strip():
            raise ValidationError({
                'whats_wrong': 'Either whats_wrong or suggestion is required.',
                'suggestion': 'Either whats_wrong or suggestion is required.',
            })

        if not Translation.objects.filter(pk=attrs['translation_id']).exists():
            raise ValidationError({
                'translation_id': 'Translation does not exist'
            })
        return super().validate(attrs)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        if 'recaptcha' in validated_data:
            validated_data.pop('recaptcha')
        return TranslationFeedback.objects.create(**validated_data)
Exemplo n.º 2
0
class FormSerializer(serializers.Serializer):
    recaptcha = ReCaptchaV2Field()
    url = serializers.URLField()
    faucet_option_id = serializers.IntegerField()

    def validate(self, attrs):
        attrs.pop("recaptcha")
        return attrs
Exemplo n.º 3
0
class ResetPasswordSerializer(serializers.ModelSerializer):
    """Reset a password"""
    username = serializers.CharField(required=True, help_text="Your username")

    recaptcha = ReCaptchaV2Field(required=not settings.NOCAPTCHA)

    class Meta:
        model = DjangoUser
        fields = ('username', 'recaptcha')
Exemplo n.º 4
0
class ContactSerializer(serializers.Serializer):
    name = CharField(max_length=150)
    email = EmailField()
    message = CharField()
    if settings.DRF_RECAPTCHA_ENABLED:
        recaptcha = ReCaptchaV2Field()

    def validate(self, data):
        data.pop("recaptcha", None)
        return data
Exemplo n.º 5
0
    class TestSerializer(Serializer):
        token = ReCaptchaV2Field()

        def is_valid(self, raise_exception=False):
            if self.request.META["HTTP_USER_AGENT"] == "WEB":
                self.context["DRF_RECAPTCHA_SECRET_KEY"] = TEST_V2_SECRET_KEY
            super(TestSerializer, self).is_valid(raise_exception)

        def validate(self, attrs):
            print(self.context.request.__dict__)
            if self.context.request.META["HTTP_USER_AGENT"] == "WEB":
                self.context["DRF_RECAPTCHA_SECRET_KEY"] = TEST_V2_SECRET_KEY
            return super().validate(attrs)
Exemplo n.º 6
0
class ContactSecureSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    email = serializers.EmailField()
    content = serializers.CharField(max_length=2000)

    recaptcha = ReCaptchaV2Field()

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        if 'recaptcha' in validated_data:
            validated_data.pop('recaptcha')
        return Contact.objects.create(**validated_data)
Exemplo n.º 7
0
class AbstractSuggestionSerializer(serializers.ModelSerializer):
    """
    Classe que serializa um modelo para sugestão de novas ações/declarações.

    Raises:
        serializers.ValidationError: Se o usuário sugerir uma tag que não está cadastrada.
    """

    tags = serializers.ListField()
    recaptcha = ReCaptchaV2Field()

    class Meta:
        fields = "__all__"

    def create(
        self, validated_data: Dict[str, Any]
    ) -> Union[ActionSuggestion, ActionSuggestionChanges, QuoteSuggestion,
               QuoteSuggestionChanges, ]:
        tags = validated_data.pop("tags", [])
        suggested = self.Meta.model.objects.create(
            **validated_data)  # type: ignore
        suggested.tags.add(*tags)
        suggested.save()
        return suggested

    def validate(self, attrs: OrderedDict[str, Any]) -> OrderedDict[str, Any]:
        attrs.pop("recaptcha", "")
        invalid_tags = []
        for tag in attrs.get("tags", []):
            qs = self.Meta.model.tags.through.tag_model().objects.filter(
                name=tag)  # type: ignore
            if not qs.exists():
                invalid_tags.append(f"'{tag}'")

        if invalid_tags:
            if len(invalid_tags) > 1:
                invalid_tags_str = (", ".join(invalid_tags[:-1]) + " e " +
                                    invalid_tags[-1])
            else:
                invalid_tags_str = invalid_tags[0]
            raise serializers.ValidationError({
                "tags":
                (f"A(s) tag(s) {invalid_tags_str} "
                 "não consta(m) na nossa base e por isso é(são) considerada(s) inválida(s). "
                 "Se você pensa que ela(s) é(são) imprescindível(is) contate-nos por "
                 f"e-mail ({settings.EMAIL_HOST_USER}).")
            })

        return attrs
Exemplo n.º 8
0
class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=140)
    password = serializers.CharField(max_length=140)
    email = serializers.EmailField(max_length=140)
    kvkk = serializers.BooleanField()
    confirm_password = serializers.CharField(max_length=140)
    recaptcha = ReCaptchaV2Field()

    def validate(self, attrs):
        if attrs.get('confirm_password') != attrs.get('password'):
            raise serializers.ValidationError('Passwords does not match')
        return attrs

    def validate_username(self, username):
        user = User.objects.filter(username=username)
        if user:
            raise serializers.ValidationError('Bu kullanıcı adı alınmış.')
        return username

    def validate_email(self, email):
        user = User.objects.filter(email=email)
        if user:
            raise serializers.ValidationError('Bu email adresi kullanımda.')
        return email

    def validate_kvkk(self, attr):
        if attr is not True:
            raise serializers.ValidationError('KVKK is have to checked')
        return attr

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
            password=make_password(validated_data['password']),
            email=validated_data['email'],
            account_type="rookie",
        )
        return LoginUserSerializer(user, many=False).data
Exemplo n.º 9
0
def test_recaptcha_v2_field_write_only(params, expected):
    field = ReCaptchaV2Field(**params)
    assert field.write_only is expected
Exemplo n.º 10
0
class V2Serializer(Serializer):
    token = ReCaptchaV2Field()
Exemplo n.º 11
0
class RequestAnonymousSerializer(serializers.ModelSerializer):
    comments = CommentDefaultSerializer(many=True, read_only=True)
    comment_text = CharField(write_only=True, required=False, allow_blank=True)
    requester_first_name = CharField(write_only=True)
    requester_last_name = CharField(write_only=True)
    requester_email = EmailField(write_only=True)
    requester_mobile = PhoneNumberField(write_only=True)
    if settings.DRF_RECAPTCHA_ENABLED:
        recaptcha = ReCaptchaV2Field()

    class Meta:
        model = Request
        fields = (
            "id",
            "title",
            "status",
            "start_datetime",
            "end_datetime",
            "type",
            "place",
            "comments",
            "comment_text",
            "requester_first_name",
            "requester_last_name",
            "requester_email",
            "requester_mobile",
        )
        read_only_fields = (
            "id",
            "status",
            "comments",
        )
        write_only_fields = (
            "comment_text",
            "requester_first_name",
            "requester_last_name",
            "requester_email",
            "requester_mobile",
        )

        if settings.DRF_RECAPTCHA_ENABLED:
            fields += ("recaptcha", )
            write_only_fields += ("recaptcha", )

    def create(self, validated_data):
        comment_text = validated_data.pop("comment_text", None)
        validated_data["requester"], additional_data = create_user(
            validated_data)
        request = super(RequestAnonymousSerializer,
                        self).create(validated_data)
        if additional_data:
            request.additional_data = additional_data
        if comment_text:
            request.comments.add(create_comment(comment_text, request))
        request.save()
        create_calendar_event.delay(request.id)
        email_user_new_request_confirmation.delay(request.id)
        return request

    def validate(self, data):
        data.pop("recaptcha", None)
        if data.get("start_datetime") < localtime():
            raise ValidationError(
                {"start_datetime": "Must be later than current time."})
        return data
Exemplo n.º 12
0
class RegisterSerializer(serializers.ModelSerializer):
    """Register a user"""
    username = serializers.CharField(
        required=True,
        help_text="Your new username",
        validators=[UniqueValidator(queryset=DjangoUser.objects.all())],
    )

    email = serializers.EmailField(required=True,
                                   help_text="Your e-mail address")

    password = serializers.CharField(write_only=True,
                                     required=True,
                                     validators=[validate_password],
                                     help_text="Your new password")
    password2 = serializers.CharField(
        write_only=True,
        required=True,
        help_text="Repeat your new password again")

    # name changed for the field to work with https://github.com/benchesh/Cookie-Notice-Blocker
    shrivacy_policy = serializers.BooleanField(
        write_only=True,
        required=False,
        help_text="I have read and I accept"
        " the privacy policy")
    recaptcha = ReCaptchaV2Field(required=not settings.NOCAPTCHA)

    class Meta:
        model = DjangoUser
        fields = ('username', 'password', 'password2', 'email', 'recaptcha',
                  'shrivacy_policy')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError(
                {"password": "******"})

        if not attrs.get('shrivacy_policy', False):
            raise serializers.ValidationError({
                'shrivacy_policy':
                "Please accept the privacy policy"
                " to sign up for Tournesol"
            })
        return attrs

    def create(self, validated_data):
        user = None
        try:
            user = DjangoUser.objects.create_user(
                username=validated_data['username'],
                email=validated_data['email'],
                password=validated_data['password'],
                is_active=False,
            )

            user_info = UserInformation.objects.create(user=user)
            email = VerifiableEmail.objects.create(email=user.email,
                                                   user=user_info,
                                                   is_verified=False)

            # creating preferences for a new user
            # return redirect(f'/email_show_instructions/{user.email}')
        except Exception as e:
            raise serializers.ValidationError({'username': [str(e)]})

        create_user_preferences()
        send_verification_email(email)

        return user