Esempio n. 1
0
class PhoneAuthenticationSerializer(serializers.Serializer):
    phone = fields.CharField(required=True, help_text='手机号')
    phone_access = fields.CharField(required=True, help_text='验证码')

    def validate(self, data):
        phone, pa = data['phone'], data['phone_access']
        try:
            access = PhoneAccess.objects.get(phone=phone, phone_access=pa)
            if phone != '17704818161':
                access.delete()
        except PhoneAccess.DoesNotExist:
            raise ValidationError('验证码错误')
        try:
            User.objects.get(username=phone)
        except User.DoesNotExist:
            raise ValidationError('用户不存在')
        return data

    def create(self, validated_data):
        user = User.objects.get(username=validated_data['phone'])
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user_logged_in.send(sender=user.__class__,
                            request=self.context['request'],
                            user=user)
        response = {'token': token}
        return response

    def update(self, instance, validated_data):
        return self.create(validated_data)

    def to_representation(self, instance):
        return instance
Esempio n. 2
0
class VerifyCodeSerializer(serializers.Serializer):
    pin = fields.CharField()
    pk = fields.CharField()

    def validate(self, data):
        token = data.get('pin')
        try:
            user = m.User.objects.get(pk=data.get('pk'))

            if user.verification_token != token:
                user.verification_tries += 1
                user.save()
                raise serializers.ValidationError(
                    {'verify': c.VERIFY_INVALID_PIN})

            if user.is_verified:
                raise serializers.ValidationError(
                    {'verify': c.VERIFY_ALREADY_VERIFIED})

            if user.verification_tries >= c.MAX_VERIFICATION_TRIES:
                raise serializers.ValidationError(
                    {'verify': c.VERIFY_MAX_TRIES})

            user.verification_tries = 0
            user.is_verified = True
            user.save()
            scim.activate_user(user)
            data['user'] = user
        except m.User.DoesNotExist:
            raise serializers.ValidationError({'verify': c.VERIFY_NOT_FOUND})

        return data
Esempio n. 3
0
class FeedbackSerializer(PotatoCaptchaSerializer):
    feedback = fields.CharField()
    platform = fields.CharField(required=False)
    chromeless = fields.CharField(required=False)
    from_url = fields.CharField(required=False)
    user = fields.Field()

    def validate(self, attrs):
        attrs = super(FeedbackSerializer, self).validate(attrs)

        if not attrs.get('platform'):
            attrs['platform'] = self.request.GET.get('dev', '')
        if self.request.user.is_authenticated():
            attrs['user'] = self.request.user
        else:
            attrs['user'] = None

        return attrs

    def validate_feedback(self, attrs, source):

        # ensure feedback is not submitted with only white spaces
        if not attrs[source].strip():
            raise serializers.ValidationError('Feedback can\'t be blank')
        return attrs
class UserSerializer(serializers.ModelSerializer):
    username = fields.CharField()
    email = fields.EmailField()
    password = fields.CharField(write_only=True)

    def create(self, validated_data):
        user = User.objects.create(username=validated_data['username'],
                                   email=validated_data['email'])
        user.set_password(validated_data['password'])
        user.save()
        return user

    def validate_password(self, value):  # pylint: disable=no-self-use
        try:
            validate_password(value)
        except ValidationError as exc:
            raise serializers.ValidationError(str(exc))
        return value

    def validate_email(self, value):  # pylint: disable=no-self-use
        if User.objects.filter(email=value).count() > 0:
            raise serializers.ValidationError('This email already exists!')
        return value

    def validate_username(self, value):  # pylint: disable=no-self-use
        if User.objects.filter(username=value).count() > 0:
            raise serializers.ValidationError('This username already exists!')
        return value

    class Meta:
        model = User
        fields = ('username', 'email', 'password')
Esempio n. 5
0
class UserCreateSerializer(serializers.ModelSerializer):
    group = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all(), write_only=True)
    password = fields.CharField(write_only=True)
    confirm_password = fields.CharField(write_only=True)

    def validate(self, data):
        if not data.get('password') or not data.get('confirm_password'):
            raise serializers.ValidationError("Please enter a password and confirm it.")
        if data.get('password') != data.get('confirm_password'):
            raise serializers.ValidationError("Passwords don't match.")
        return data

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
    )

        validated_data['group'].user_set.add(user)
        user.set_password(validated_data['password'])
        user.save()
        return user

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'confirm_password', 'group']
Esempio n. 6
0
class ConfigurationSerializer(serializers.Serializer):
    priority = fields.ChoiceField(PRIORITY)
    scheduler = fields.ChoiceField(SCHEDULER_TYPE)
    max_tasks = fields.IntegerField(min_value=1)
    weight = fields.ChoiceField(DECISION_WEIGHT)

    parallelism = fields.ListField(child=fields.RegexField(r'^\d+(\.\d+)?$'),
                                   min_length=4,
                                   max_length=4)

    memory = fields.FloatField()
    cpu_num = fields.IntegerField(allow_null=True, min_value=1)
    disk_size = fields.FloatField()
    cpu_model = fields.CharField(default='', allow_null=True, allow_blank=True)
    cpu_time_exec_cmds = fields.FloatField()
    memory_exec_cmds = fields.FloatField()

    console_level = fields.ChoiceField(LOGGING_LEVELS)
    file_level = fields.ChoiceField(LOGGING_LEVELS)
    console_formatter = fields.CharField()
    file_formatter = fields.CharField()

    keep_intermediate_files = fields.BooleanField()
    upload_verifier_files = fields.BooleanField()
    upload_other_files = fields.BooleanField()
    ignore_subjobs = fields.BooleanField()
    total_coverage = fields.BooleanField()
    coverage_details = fields.ChoiceField(COVERAGE_DETAILS)

    def create(self, validated_data):
        raise NotImplementedError

    def update(self, instance, validated_data):
        raise NotImplementedError
Esempio n. 7
0
File: copy.py Progetto: tnir/wagtail
class CopyPageAPIActionSerializer(Serializer):
    # Note: CopyPageAction will validate the destination page
    destination_page_id = fields.IntegerField(required=False)
    recursive = fields.BooleanField(default=False, required=False)
    keep_live = fields.BooleanField(default=True, required=False)
    slug = fields.CharField(required=False)
    title = fields.CharField(required=False)
Esempio n. 8
0
class FactsSerializer(Serializer):
    """Serializer for HBI facts."""

    source_types = fields.ListField()
    last_discovered = fields.DateTimeField()
    qpc_server_version = fields.CharField(default=server_version)
    qpc_server_id = fields.CharField(default=get_server_id)
Esempio n. 9
0
class StockTransferOutSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    detail = StockTransferOutDetailSerializer(source='list_detail', many=True, read_only=True)
    created_at = fields.DateTimeField(read_only=True)
    created_by_detail = UserSerializer(read_only=True, source='created_by')
    created_by__id = fields.CharField(read_only=True)
    total = fields.IntegerField(read_only=True)
    promotion__id = fields.IntegerField(required=False, read_only=True)
    promotion_detail = PromotionSerializer(read_only=True, source='promotion')
    customer_detail = CustomerSerializer(read_only=True, source='customer')
    customer__id = fields.CharField(read_only=True)

    def validate_promotion_code(self, promotion_code):
        if promotion_code is None or promotion_code == "":
            return None
        promotions = Promotion.objects.filter(code=promotion_code)
        if promotions.count() == 0:
            raise ValidationError('promotion does not exist')
        if promotions[0].is_used:
            raise ValidationError('promotion is used')
        return promotion_code

    class Meta:
        model = StockTransferOut
        fields = '__all__'
Esempio n. 10
0
class QuoteSerializer(serializers.Serializer):
    id = fields.IntegerField(read_only=True)
    text = fields.CharField()
    author = fields.CharField(max_length=300)

    def create(self, validated_data):
        return Quote.objects.create(**validated_data)
Esempio n. 11
0
class PersonsListSerializer(Serializer):
    name = fields.CharField(required=True)
    last_name = fields.CharField(required=True)
    phone_number = fields.CharField(required=True)
    timestamp = fields.DateTimeField(required=True)
    address = fields.CharField(required=True)
    review = fields.SerializerMethodField()

    def get_review(self, obj):
        inst = obj.reviews.order_by('timestamp').last()
        if inst is not None:
            review = {
                'text': inst.text,
                'author': '{} {}'.format(inst.author.name,
                                         inst.author.last_name),
                'rating': inst.rating,
                'timestamp': inst.timestamp.isoformat(),
                'rewies_count': obj.reviews.count(),
            }
        else:
            review = {
                'text': 'There are no reviews yet',
                'rewies_count': 0,
            }
        return review
Esempio n. 12
0
class FacebookSerializer(serializers.Serializer):
    id = fields.IntegerField(read_only=True)
    access_token = fields.CharField(max_length=255)
    auth_token = fields.CharField(max_length=255, read_only=True)

    def save(self, **kwargs):
        pass
Esempio n. 13
0
class GenericMailSerializer(serializers.Serializer):
    """
    Serializer for generic email requests
    """
    email_subject = fields.CharField(label="Email Subject")
    email_body = fields.CharField(label="Email Body",
                                  style={"base_template": "textarea.html"})
Esempio n. 14
0
class UserSerializer(Serializer):
    email = fields.EmailField()
    lastname = fields.CharField()
    firstname = fields.CharField()
    is_active = fields.BooleanField(default=False)
    is_superuser = fields.BooleanField(default=False)
    is_staff = fields.BooleanField(default=True)
Esempio n. 15
0
class HistorySerializerMixIn(Serializer):
    history_id = fields.IntegerField()
    history_date = fields.DateTimeField()
    history_change_reason = fields.CharField()
    history_type = fields.CharField()
    history_user_id = fields.IntegerField()
    history_user = UserSerializer()

    class Meta:
        fields = ('history_id', 'history_date', 'history_change_reason',
                  'history_type', 'history_type', 'history_user_id',
                  'history_user')

    def to_representation(self, instance):
        ret = OrderedDict()
        fields = self._readable_fields  # noqa

        for field in fields:
            simplify_nested_serializer(field)
            try:
                attribute = field.get_attribute(instance)
                if attribute is not None:
                    ret[field.field_name] = field.to_representation(attribute)
                else:
                    ret[field.field_name] = None
            except AttributeError:
                ret[field.field_name] = None

        return ret
Esempio n. 16
0
class MedidasSerializar(serializers.EmbeddedDocumentSerializer):
    tipo_producto = fields.CharField(required=False)
    unidad_medida = fields.CharField(required=False)
    cantidad_medida = fields.IntegerField(required=False)

    class Meta:
        model = Medidas
        fields = "__all__"
Esempio n. 17
0
class YupanaMetadataSerializer(Serializer):
    """Serializer for yupana metadata."""

    report_id = fields.UUIDField(source="report_uuid")
    host_inventory_api_version = fields.CharField(default="1.0")
    source = fields.CharField(default="qpc")
    source_metadata = YupanaSourceSerializer(source="*")
    report_slices = fields.DictField(source="slices", child=ReportSliceSerializer())
Esempio n. 18
0
class MerchandiseTypeSerializer(ModelSerializer):
    id = fields.CharField(required=False)
    type_for = fields.IntegerField(read_only=True)
    description = fields.CharField(required=False, allow_blank=True)

    class Meta:
        model = MerchandiseType
        fields = '__all__'
Esempio n. 19
0
class ProjectSerializer(serializers.ModelSerializer):
    id = fields.IntegerField(required=True)
    title = fields.CharField(read_only=True)
    description = fields.CharField(read_only=True)

    class Meta:
        model = Project
        fields = ('title', 'description', 'id')
Esempio n. 20
0
class ImageSerializer(Serializer):
    pk = fields.IntegerField()
    name = fields.CharField()
    url = fields.URLField()
    web_url = fields.ImageField()
    # image_thumbnail = fields.ImageField()
    variant = fields.CharField()
    main_image = fields.BooleanField()
Esempio n. 21
0
class YupanaSourceSerializer(Serializer):
    """Format source_metadata for yupana payload."""

    report_platform_id = fields.UUIDField(source="report_uuid")
    report_type = fields.CharField(default="insights")
    report_version = fields.CharField()
    qpc_server_report_id = fields.IntegerField(source="report_id")
    qpc_server_version = fields.CharField(default=server_version)
    qpc_server_id = fields.CharField(default=get_server_id)
Esempio n. 22
0
class PassengerSerializer(serializers.ModelSerializer):
    id = fields.IntegerField(required=True)

    first_name = fields.CharField(read_only=True)
    last_name = fields.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name')
Esempio n. 23
0
 class Meta:
     param_fields = (
         ('name', fields.CharField(label='名称', max_length=64)),
         ('description', fields.CharField(label='描述', max_length=255)),
         ('create_user_manager',
          fields.BooleanField(label='创建人管理权限',
                              required=False,
                              default=False)),
     )
Esempio n. 24
0
 class Meta:
     param_fields = (
         ('name', fields.CharField(label='名称', max_length=64)),
         ('description',
          fields.CharField(label='描述',
                           max_length=255,
                           required=False,
                           default="")),
     )
Esempio n. 25
0
class PresetsArgsSerializer(Serializer):
    class Meta:
        list_serializer_class = PresetArgsListSerializer

    slug = fields.SlugField()
    label = fields.CharField()
    help_text = fields.CharField(required=False)
    placehorlder = fields.CharField(required=False)
    types = fields.ListField()
class UserUpdateSerializer(UserCreateSerializer):
  password = fields.CharField(write_only=True, validators=[PasswordReuse()])
  current_password = fields.CharField(write_only=True)
  profile = get_profile_serializers()[0](required=False)

  class Meta:
    model = models.User
    permission_classes = (permissions.IsAuthenticated,)
    fields = ['name', 'phone', 'phone2', 'password', 'avatar', 'current_password', 'locale', 'profile', 'public', 'is_subscribed_to_newsletter']
    extra_kwargs = {'password': {'write_only': True}}


  def validate(self, data):
    errors = dict()

    if data.get('password') or data.get('current_password'):
      current_password = data.pop('current_password', '')
      password = data.get('password', '')

      try:
        validate_password(password=password)
      except ValidationError as e:
        errors['password'] = list(e.messages)

      if not authenticate(email=self.context['request'].user.email, password=current_password, channel=self.context["request"].channel):
        errors['current_password'] = ["Invalid password."]

    if errors:
      raise serializers.ValidationError(errors)

    return super(UserCreateSerializer, self).validate(data)

  def update(self, instance, data):
    ProfileModel = get_profile_model()
    profile_data = data.pop('profile', None)

    if profile_data:
      has_profile=False
      try:
        if instance.profile:
          has_profile=True
        else:
          has_profile=False
      except models.UserProfile.DoesNotExist:
        has_profile=False

      if has_profile:
        profile = instance.profile
      else:
        profile = ProfileModel(user=instance)
        profile.save(object_channel=self.context["request"].channel)

      profile_sr = get_profile_serializers()[0](profile, data=profile_data, partial=True)
      profile_sr.is_valid(raise_exception=True)
      profile = profile_sr.update(profile, profile_sr.validated_data)

    return super(UserUpdateSerializer, self).update(instance, data)
Esempio n. 27
0
class AdminSettingSerializer(serializers.MongoEngineModelSerializer):
    name = fields.CharField(source='name')
    yes_no = fields.BooleanField(source='yes_no', default=True)
    value_str = fields.CharField(source='value_str', required=False)
    value_int = fields.IntegerField(source='value_int', required=False)

    class Meta:
        model = AdminSetting
        fields = ('name', 'yes_no', 'value_str', 'value_int')
Esempio n. 28
0
 class Meta:
     param_fields = (
         ('room_id', fields.IntegerField(label='会议室ID')),
         ('name', fields.CharField(label='名称', max_length=64)),
         ('description', fields.CharField(label='描述', max_length=255, required=False, default="")),
         ('date', fields.DateField(label='预定日期')),
         ('start_time', fields.TimeField(label='开始时间')),
         ('end_time', fields.TimeField(label='结束时间')),
     )
Esempio n. 29
0
class DetalleUnitarioSerializer(serializers.EmbeddedDocumentSerializer):
    cantidad_unitaria = fields.IntegerField(required=False)
    nombre_sub_presentacion = fields.CharField(required=False)
    unidad_medida = fields.CharField(required=False)
    precio_unidad = fields.FloatField(required=False)

    class Meta:
        model = DetalleUnitario
        fields = "__all__"
Esempio n. 30
0
class BulkUserProfileSerializer(BulkSerializerMixin, serializers.MongoEngineModelSerializer):
    name = fields.CharField(source='name', required=True)
    phone = fields.CharField(source='phone', required=True)
    email = fields.CharField(source='email', required=False)
    location = fields.Field(source='location')

    class Meta(object):
        model = UserProfile
        exclude = ('created_at',)