class AuthorizationSerializer(serializers.Serializer): """Serializer авторизации пользователя""" username = serializers.CharField(required=True) password = serializers.CharField(required=True) recaptcha = ReCaptchaV3Field(action="authorization") def validate(self, attrs): super().validate(attrs) error_text = "Неверные имя пользователя и/или пароль." try: self.user = User.objects.get(username=attrs["username"]) if not self.user.is_active: raise serializers.ValidationError(error_text) except User.DoesNotExist: raise serializers.ValidationError(error_text) if not self.user.check_password(attrs["password"]): raise serializers.ValidationError(error_text) return attrs def get_tokens(self): return generate_tokens(self.user)
def test_recaptcha_v3_field_score_priority( params, from_settings, settings_default, expected, settings ): settings.DRF_RECAPTCHA_ACTION_V3_SCORES = from_settings settings.DRF_RECAPTCHA_DEFAULT_V3_SCORE = settings_default field = ReCaptchaV3Field(action="test_action", **params) assert field.required_score == expected
class RecaptchaEnabledUserRegisterSerializer(UserRegisterSerializer): recaptcha = ReCaptchaV3Field(action="register") class Meta(UserRegisterSerializer.Meta): fields = UserRegisterSerializer.Meta.fields + ("recaptcha", ) def validate(self, attrs): attrs.pop("recaptcha") return super().validate(attrs)
def test_recaptcha_v3_field_score_improperly_configured( params, from_settings, settings_default, error, settings ): settings.DRF_RECAPTCHA_ACTION_V3_SCORES = from_settings settings.DRF_RECAPTCHA_DEFAULT_V3_SCORE = settings_default with pytest.raises(ImproperlyConfigured) as exc_info: ReCaptchaV3Field(action="test_action", **params) assert str(exc_info.value) == error
class RegistrationSerializer(serializers.ModelSerializer): """Serializer регистрациия пользователя""" password_1 = serializers.CharField(required=True) password_2 = serializers.CharField(required=True) recaptcha = ReCaptchaV3Field(action="registration") def validate(self, attrs): super().validate(attrs) try: User.objects.get(username=attrs["username"]) raise serializers.ValidationError( "Пользователь с таким именем уже существует.") except User.DoesNotExist: if attrs["username"].lower() in ("authorization", "registration", "games", "users", "edit", "change-password", "delete", "friends", "views", "party-list", "google-oauth2", "vk-oauth2", "гость", "черный", "белый"): raise serializers.ValidationError( "Имя пользователя совпадает с ключевой фразой.") validate_password(attrs["password_1"]) if attrs["password_1"] != attrs["password_2"]: raise serializers.ValidationError("Пароли не совпадают.") validate_email(attrs["email"]) try: User.objects.get(email=attrs["email"]) raise serializers.ValidationError( "Пользователь с такой эл. почтой уже существует.") except User.DoesNotExist: return attrs def save(self): user = User.objects.create(username=self.validated_data["username"], email=self.validated_data["email"]) user.set_password(self.validated_data["password_1"]) user.save() get_or_create_chat(user, user) return generate_tokens(user) class Meta: model = User fields = ("username", "email", "password_1", "password_2", "recaptcha")
class LeadValidator(validators.Validator): name = validators.CharField(required=False) email = validators.EmailField(required=True) recaptcha = ReCaptchaV3Field(action='lead_magnet', ) class Meta: fields = [ 'name', 'email', ] def validate(self, attrs): attrs.pop('recaptcha') return attrs
class UserSerializer(UserPublicSerializer): email = serializers.EmailField() password = serializers.CharField(write_only=True, style={'input_type': 'password', 'placeholder': 'Password'}) recaptcha = ReCaptchaV3Field(action="register") detail = UserDetailSerializer(read_only=True) class Meta(UserPublicSerializer.Meta): fields = UserPublicSerializer.Meta.fields + ['password', 'email', 'recaptcha', 'detail'] def validate(self, attrs): attrs.pop('recaptcha', None) return attrs def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data)
def test_recaptcha_v3_field_write_only(params, expected): field = ReCaptchaV3Field(action="test_action", **params) assert field.write_only is expected
class TestSerializer(Serializer): token = ReCaptchaV3Field(action="test_action")