def validate_age(self, age):
     if age < 0:
         raise serializers.ValidationError(
             "age cannot be negative or null value")
     return age
Esempio n. 2
0
    def validate(self, attrs):
        user = self.context['request'].user
        if user != self.instance.user:
            raise serializers.ValidationError({'error': '仅创建者可以修改'})

        return attrs
Esempio n. 3
0
 def validate_email(self, value):
     if User.objects.filter(email=value).exists():
         raise serializers.ValidationError('This email is already exists!')
     return value
Esempio n. 4
0
 def validate(self, data):
     user = authenticate(**data)
     if user and user.is_active:
         return user
     raise serializers.ValidationError("Verify your credentials!")
Esempio n. 5
0
    def validate_actor_name(self, value):
        if value not in get_declared_actors():
            raise serializers.ValidationError('Unknown actor name')

        return value
 def get_point(self, attrs):
     try:
         return point.Point(attrs['longitude'], attrs['latitude'])
     except (TypeError, ValueError):
         raise serializers.ValidationError("Invalid geo_json point")
    def validate(self, data):
        if data['revision'] is None and data['interval'] is None and (
                data['startday'] is None or data['endday'] is None):
            raise serializers.ValidationError('Required: revision, startday and endday or interval.')

        return data
Esempio n. 8
0
 def validate_new_password(self, value):
     if len(value) < 8:
         raise serializers.ValidationError("비밀번호는 8글자 이상이어야 합니다.")
     return value
    def validate(self, attrs):
        view = self.context.get("view")
        request = self._get_request()

        if not view:
            raise serializers.ValidationError(
                "View is not defined, pass it as a context variable")

        adapter_class = getattr(view, "adapter_class", None)
        if not adapter_class:
            raise serializers.ValidationError("Define adapter_class in view")

        adapter = adapter_class(request)
        app = adapter.get_provider().get_app(request)

        # More info on code vs access_token
        # http://stackoverflow.com/questions/8666316/facebook-oauth-2-0-code-and-token

        # Case 1: We received the access_token
        if attrs.get("access_token"):
            access_token = attrs.get("access_token")
            token = {"access_token": access_token}

        # Case 2: We received the authorization code
        elif attrs.get("code"):
            self.callback_url = getattr(view, "callback_url", None)
            self.client_class = getattr(view, "client_class", None)

            if not self.callback_url:
                raise serializers.ValidationError(
                    "Define callback_url in view")
            if not self.client_class:
                raise serializers.ValidationError(
                    "Define client_class in view")

            code = attrs.get("code")

            provider = adapter.get_provider()
            scope = provider.get_scope(request)
            client = self.client_class(
                request,
                app.client_id,
                app.secret,
                adapter.access_token_method,
                adapter.access_token_url,
                self.callback_url,
                scope,
                key=app.key,
                cert=app.cert,
            )
            token = client.get_access_token(code)
            access_token = token["access_token"]

        else:
            raise serializers.ValidationError(
                "Incorrect input. access_token or code is required.")

        # Custom changes introduced to handle apple login on allauth
        try:
            social_token = adapter.parse_token({
                "access_token":
                access_token,
                "id_token":
                attrs.get("id_token"),  # For apple login
            })
            social_token.app = app
        except OAuth2Error as err:
            raise serializers.ValidationError(str(err)) from err

        try:
            login = self.get_social_login(adapter, app, social_token,
                                          access_token)
            complete_social_login(request, login)
        except HTTPError:
            raise serializers.ValidationError("Incorrect value")

        if not login.is_existing:
            # We have an account already signed up in a different flow
            # with the same email address: raise an exception, for security reasons.
            # If you decide to follow up with this flow, checkout allauth implementation:
            # add login.connect(request, email_address.user)
            # https://github.com/pennersr/django-allauth/issues/1149
            #
            # if allauth_settings.UNIQUE_EMAIL:
            #     # Do we have an account already with this email address?
            #     if get_user_model().objects.filter(email=login.user.email).exists():
            #         raise serializers.ValidationError(
            #             'E-mail already registered using different signup method.')

            login.lookup()
            login.save(request, connect=True)

        attrs["user"] = login.account.user
        return attrs
Esempio n. 10
0
 def validate_type(self, type):
     if type not in string_to_action_type:
         raise serializers.ValidationError(
             "Invalid type, valid values are [%s]" % ", ".join(string_to_action_type.keys())
         )
     return string_to_action_type[type]
Esempio n. 11
0
    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("중복된 아이디입니다.")

        return value
Esempio n. 12
0
    def validate(self, data):
        """
        Performs validation on an alert rule's data.
        This includes ensuring there is either 1 or 2 triggers, which each have
        actions, and have proper thresholds set. The critical trigger should
        both alert and resolve 'after' the warning trigger (whether that means
        > or < the value depends on threshold type).
        """
        data.setdefault("dataset", QueryDatasets.EVENTS)
        project_id = data.get("projects")
        if not project_id:
            # We just need a valid project id from the org so that we can verify
            # the query. We don't use the returned data anywhere, so it doesn't
            # matter which.
            project_id = list(self.context["organization"].project_set.all()[:1])
        try:
            snuba_filter = build_snuba_filter(
                data["dataset"],
                data["query"],
                data["aggregate"],
                data.get("environment"),
                data.get("event_types"),
                params={
                    "project_id": [p.id for p in project_id],
                    "start": timezone.now() - timedelta(minutes=10),
                    "end": timezone.now(),
                },
            )
            if any(cond[0] == "project_id" for cond in snuba_filter.conditions):
                raise serializers.ValidationError({"query": "Project is an invalid search term"})
        except (InvalidSearchQuery, ValueError) as e:
            raise serializers.ValidationError(f"Invalid Query or Metric: {e}")
        else:
            if not snuba_filter.aggregations:
                raise serializers.ValidationError(
                    "Invalid Metric: Please pass a valid function for aggregation"
                )

            try:
                raw_query(
                    aggregations=snuba_filter.aggregations,
                    start=snuba_filter.start,
                    end=snuba_filter.end,
                    conditions=snuba_filter.conditions,
                    filter_keys=snuba_filter.filter_keys,
                    having=snuba_filter.having,
                    dataset=Dataset(data["dataset"].value),
                    limit=1,
                    referrer="alertruleserializer.test_query",
                )
            except Exception:
                logger.exception("Error while validating snuba alert rule query")
                raise serializers.ValidationError(
                    "Invalid Query or Metric: An error occurred while attempting "
                    "to run the query"
                )

        triggers = data.get("triggers", [])
        if not triggers:
            raise serializers.ValidationError("Must include at least one trigger")
        if len(triggers) > 2:
            raise serializers.ValidationError(
                "Must send 1 or 2 triggers - A critical trigger, and an optional warning trigger"
            )

        event_types = data.get("event_types")

        valid_event_types = dataset_valid_event_types[data["dataset"]]
        if event_types and set(event_types) - valid_event_types:
            raise serializers.ValidationError(
                "Invalid event types for this dataset. Valid event types are %s"
                % sorted(et.name.lower() for et in valid_event_types)
            )

        for i, (trigger, expected_label) in enumerate(
            zip(triggers, (CRITICAL_TRIGGER_LABEL, WARNING_TRIGGER_LABEL))
        ):
            if trigger.get("label", None) != expected_label:
                raise serializers.ValidationError(
                    f'Trigger {i + 1} must be labeled "{expected_label}"'
                )
        critical = triggers[0]
        threshold_type = data["threshold_type"]

        self._validate_trigger_thresholds(threshold_type, critical, data.get("resolve_threshold"))

        if len(triggers) == 2:
            warning = triggers[1]
            self._validate_trigger_thresholds(
                threshold_type, warning, data.get("resolve_threshold")
            )
            self._validate_critical_warning_triggers(threshold_type, critical, warning)

        return data
Esempio n. 13
0
    def email_validate(email):
        regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"

        if not re.match(regex, email):
            raise serializers.ValidationError(errors['email']['invalid'])
Esempio n. 14
0
 def validate(self, data):
     if data['password'] != data['password2']:
         raise serializers.ValidationError(
             {"password": "******"})
     return data
Esempio n. 15
0
 def validate_name(self, value):
     if value.isalpha():
         return value
     raise serializers.ValidationError("Name should contain only alphabets")
Esempio n. 16
0
 def validate_password2(self, data):
     if data != self.initial_data["password"]:
         raise serializers.ValidationError("密码不一致")
     else:
         return data
Esempio n. 17
0
 def validate_type(self, value):
     if 1 < value > 3:
         raise serializers.ValidationError('Type options: [1, 2, 3]')
     return value
Esempio n. 18
0
 def validate_mobile(self, attrs):
     if not re.match(r'1[3-9]\d{9}',attrs):
         raise serializers.ValidationError('格式错误')
     else:
         return attrs
Esempio n. 19
0
    def _update_or_create(self, operation, instance, validated_data):
        filters = validated_data.pop('filter_defs', None)
        comment = validated_data.pop('comment', None)
        previous_index = None
        new_index = None
        index_max = RuleProcessingFilter.objects.aggregate(models.Max('index'))['index__max']

        if operation == 'create':
            if not filters:
                # Error on null and empt list
                raise serializers.ValidationError({'filter_defs': ['This field is required.']})

            if validated_data.get('index') is None:
                if index_max is None:
                    validated_data['index'] = 0
                else:
                    validated_data['index'] = index_max + 1
                    
            else:
                new_index = validated_data['index']
                if new_index != 0 and (index_max is None or new_index > index_max + 1):
                    raise serializers.ValidationError({'index': ['Invalid index value (too high).']})

            instance = super(RuleProcessingFilterSerializer, self).create(validated_data)
            user_action = 'create'

            if self.option_serializer and hasattr(self.option_serializer.Meta.model, 'action'):
                self.option_serializer.save(action=instance)
        else:
            if filters is not None and len(filters) == 0:
                # Error on empty list only
                raise serializers.ValidationError({'filter_defs': ['This field is required.']})

            if 'index' in validated_data:
                previous_index = instance.index
                new_index = validated_data['index']
                if new_index is None:
                    new_index = index_max + 1
                    validated_data['index'] = new_index
                elif new_index > index_max + 1:
                    raise serializers.ValidationError({'index': ['Invalid index value (too high).']})

            instance = super(RuleProcessingFilterSerializer, self).update(instance, validated_data)
            user_action = 'edit'

        self._reorder(instance, previous_index, new_index)

        if filters:
            try:
                self._set_filters(instance, filters)
            except:
                if operation == 'create':
                    instance.delete()
                raise

        UserAction.create(
                action_type='%s_rule_filter' % user_action,
                comment=comment,
                user=self.context['request'].user,
                rule_filter=instance
        )
        return instance
Esempio n. 20
0
    def update(self, instance, validated_data):
        fields_data = self.context.get('fields')
        method = str(self.context['request'].method)

        if (method == "PATCH"):
            if fields_data:
                for field in fields_data:
                    field_id = None
                    try:
                        if field['id']:
                            field_id = field['id']
                    except KeyError:
                        pass
                    # if id exists, patch existing field
                    if field_id:
                        try:
                            field_to_update = instance.fields.get_subclass(
                                id=field_id)

                            field_type = None
                            try:
                                field_type = field['field_type']

                            except KeyError:
                                pass

                            # patch if the field type is the same or none
                            if field_type == translate_field_type(
                                    field_to_update) or field_type is None:
                                field_name = field['name']
                                field_to_update.name = field_name
                                field_to_update.save()
                            else:
                                message = 'Can\'t patch a field with a different'
                                message += ' type (' + field_to_update.name + ')'
                                raise serializers.ValidationError(message)

                        except GenericField.DoesNotExist:
                            message = 'Could fidnt a field with the referenced id'
                            message += ' (' + str(field_id) + ')'
                            raise serializers.ValidationError(message)
                    # otherwise, create a whole new field
                    else:
                        try:
                            self.validate_fields(fields_data)
                        except KeyError:
                            message = "Insufficient data"
                            raise serializers.ValidationError(message)

                        field_type = field['field_type']
                        field_name = field['name']
                        risktype = instance
                        if field_type == 'text':
                            TextField.objects.create(name=field_name,
                                                     risktype=risktype)
                        elif field_type == 'number':
                            NumberField.objects.create(name=field_name,
                                                       risktype=risktype)
                        elif field_type == 'date':
                            DateField.objects.create(name=field_name,
                                                     risktype=risktype)
                        elif isinstance(field_type, (list, )):
                            EnumField.objects.create(name=field_name,
                                                     choices=field_type,
                                                     risktype=risktype)

        elif (method == "PUT"):
            try:
                if not validated_data['name']:
                    message = "RiskType name missing"
                    raise serializers.ValidationError(message)
            except KeyError:
                message = "RiskType name missing"
                raise serializers.ValidationError(message)

            if fields_data:
                instance.fields.all().delete()
                risktype = instance
                for field in fields_data:
                    field_type = field['field_type']
                    field_name = field['name']
                    if field_type == 'text':
                        TextField.objects.create(name=field_name,
                                                 risktype=risktype)
                    elif field_type == 'number':
                        NumberField.objects.create(name=field_name,
                                                   risktype=risktype)
                    elif field_type == 'date':
                        DateField.objects.create(name=field_name,
                                                 risktype=risktype)
                    elif isinstance(field_type, (list, )):
                        EnumField.objects.create(name=field_name,
                                                 choices=field_type,
                                                 risktype=risktype)

        instance = super(RiskTypeSerializer,
                         self).update(instance, validated_data)
        return instance
Esempio n. 21
0
    def validate(self, data):

        if not data['maintenance_flag']:
            return data

        if data['category'] not in defs.SYSTEM_SETTINGS.CATEGORY_LIST:
            raise serializers.ValidationError("不明なカテゴリー categ=%s" % (data['category']))

        if data['category'] == 'LOG_STORAGE_PERIOD':
            if isinstance(data['value'], int):
                data['value'] = str(data['value'])

            if not isinstance(data['value'], str):
                raise serializers.ValidationError("予期せぬ型(ログ保存日数) type=%s, val=%s" % (type(data['value']), data['value']))

            if not data['value'].isdigit():
                raise serializers.ValidationError("数値以外の値(ログ保存日数) val=%s" % (data['value']))

            val_tmp = int(data['value'])
            if val_tmp < self.LOG_STORAGE_PERIOD_MIN or val_tmp > self.LOG_STORAGE_PERIOD_MAX:
                raise serializers.ValidationError("無効なログ保存日数 val=%s" % (val_tmp))

        if data['category'] == 'SESSION_TIMEOUT':
            if isinstance(data['value'], int):
                data['value'] = str(data['value'])

            if not isinstance(data['value'], str):
                raise serializers.ValidationError("予期せぬ型(セッションタイムアウト値) type=%s, val=%s" % (type(data['value']), data['value']))

            if not data['value'].isdigit():
                raise serializers.ValidationError("数値以外の値(セッションタイムアウト値) val=%s" % (data['value']))

            val_tmp = int(data['value'])
            if val_tmp < self.SESSION_TIMEOUT_MIN or val_tmp > self.SESSION_TIMEOUT_MAX:
                raise serializers.ValidationError("無効なセッションタイムアウト値 val=%s" % (val_tmp))

        if data['category'] == 'PASSWORD':
            if data['config_id'] == 'Pass_Valid_Period':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(パスワード有効期間) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(パスワード有効期間) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.PASSWORD_LIFETIME_MIN or val_tmp > self.PASSWORD_LIFETIME_MAX:
                    raise serializers.ValidationError("無効なパスワード有効期間 val=%s" % (val_tmp))

                if len(data['value']) > 1 and data['value'][0] == '0':
                    raise serializers.ValidationError("無効なパスワード有効期間 val=%s" % (data['value']))

            if data['config_id'] == 'Pass_generate_manage':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(同一パスワード設定不可世代数) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(同一パスワード設定不可世代数) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.PASSWORD_GENERATION_MIN or val_tmp > self.PASSWORD_GENERATION_MAX:
                    raise serializers.ValidationError("無効な同一パスワード設定不可世代数 val=%s" % (val_tmp))

            if data['config_id'] == 'PASS_ERROR_THRESHOLD':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(パスワード誤り閾値) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(パスワード誤り閾値) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.PASS_ERROR_THRESHOLD_MIN or val_tmp > self.PASS_ERROR_THRESHOLD_MAX:
                    raise serializers.ValidationError("無効なパスワード誤り閾値 val=%s" % (val_tmp))
                
                if len(data['value']) > 1 and data['value'][0] == '0':
                    raise serializers.ValidationError("無効なパスワード誤り閾値 val=%s" % (data['value']))

            if data['config_id'] == 'ACCOUNT_LOCK_PERIOD':
            
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(アカウントロック継続期間) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(アカウントロック継続期間) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.ACCOUNT_LOCK_PERIOD_MIN or val_tmp > self.ACCOUNT_LOCK_PERIOD_MAX:
                    raise serializers.ValidationError("無効なアカウントロック継続期間 val=%s" % (val_tmp))

                if len(data['value']) > 1 and data['value'][0] == '0':
                    raise serializers.ValidationError("無効なアカウントロック継続期間 val=%s" % (data['value']))

            if data['config_id'] == 'INITIAL_PASS_VALID_PERIOD':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(初期パスワード有効期間) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(初期パスワード有効期間) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.PASSWORD_INITTIME_MIN or val_tmp > self.PASSWORD_INITTIME_MAX:
                    raise serializers.ValidationError("無効な初期パスワード有効期間 val=%s" % (val_tmp))
            if data['config_id'] == 'ACCOUNT_LOCK_MAX_TIMES':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(アカウントロック上限回数) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(アカウントロック上限回数) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.ACCOUNT_LOCK_MAX_TIMES_MIN or val_tmp > self.ACCOUNT_LOCK_MAX_TIMES_MAX:
                    raise serializers.ValidationError("無効なアカウントロック上限回数 val=%s" % (val_tmp))
            if data['config_id'] == 'NOTIFICATION_DESTINATION_TYPE':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(メール通知種別) type=%s, val=%s" % (type(data['value']), data['value']))

                if not (data['value'] in ('0','1','2')):
                    raise serializers.ValidationError("予期せぬ型(メール通知種別) type=%s, val=%s" % (type(data['value']), data['value']))

            # ログインID形式チェック
            if data['config_id'] == 'NOTIFICATION_DESTINATION':

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(メール通知先ログインID) type=%s, val=%s" % (type(data['value']), data['value']))

                # 絵文字チェック
                value_list = self.EMO_CHK.is_emotion(data['value'])
                if len(value_list) > 0:
                    raise serializers.ValidationError("メール通知先ログインIDに使用できない文字が含まれています。")

            # 同一IP連続ログイン試行上限チェック
            if data['config_id'] == 'IPADDR_LOGIN_RETRY_MAX':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(同一IPアドレス連続ログイン試行上限) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(同一IPアドレス連続ログイン試行上限) val=%s" % (data['value']))

                val_tmp = int(data['value'])
                if val_tmp < self.IPADDR_LOGIN_RETRY_MIN or val_tmp > self.IPADDR_LOGIN_RETRY_MAX:
                    raise serializers.ValidationError("無効な同一IPアドレス連続ログイン試行上限 val=%s" % (val_tmp))


        if data['category'] == 'ACTIVE_DIRECTORY':
            if data['config_id'] == 'ADCOLLABORATION':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(Active Directory連携値) type=%s, val=%s" % (type(data['value']), data['value']))

                if data['value'] not in self.DISUSEFLAG_LIST:
                    raise serializers.ValidationError("無効なActive Directory連携値 val=%s" % (data['value']))

            if data['config_id'] == 'ADMINISTRATOR_USER':
                value_len = len(data['value'])
                if value_len < 1:
                    raise serializers.ValidationError("管理者ユーザは必須項目です")

                # 絵文字チェック
                value_list = self.EMO_CHK.is_emotion(data['value'])
                if len(value_list) > 0:
                    raise serializers.ValidationError("管理者ユーザに使用できない文字が含まれています。")

            if data['config_id'] == 'ADMINISTRATOR_PW':
                value_len = len(data['value'])
                if value_len < 1:
                    raise serializers.ValidationError("管理者パスワードは必須項目です")

                # 絵文字チェック
                value_list = self.EMO_CHK.is_emotion(data['value'])
                if len(value_list) > 0:
                    raise serializers.ValidationError("管理者パスワードに使用できない文字が含まれています。")

            if data['config_id'] == 'ACCESS_POINT':
                value_len = len(data['value'])
                if value_len < 1:
                    raise serializers.ValidationError("接続先は必須項目です")

                # 絵文字チェック
                value_list = self.EMO_CHK.is_emotion(data['value'])
                if len(value_list) > 0:
                    raise serializers.ValidationError("接続先に使用できない文字が含まれています。")

            if data['config_id'] == 'CONNECTION_TIMEOUT':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(接続タイムアウト値) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(接続タイムアウト値) val=%s" % (data['value']))

            if data['config_id'] == 'READ_TIMEOUT':
                if isinstance(data['value'], int):
                    data['value'] = str(data['value'])

                if not isinstance(data['value'], str):
                    raise serializers.ValidationError("予期せぬ型(読み取りタイムアウト値) type=%s, val=%s" % (type(data['value']), data['value']))

                if not data['value'].isdigit():
                    raise serializers.ValidationError("数値以外の値(読み取りタイムアウト値) val=%s" % (data['value']))

            if data['config_id'] == 'AUTHSERVER_SEARCH_CHAR':
                value_len = len(data['value'])
                if value_len < 1:
                    raise serializers.ValidationError("認証サーバ検索文字は必須項目です")

                # 絵文字チェック
                value_list = self.EMO_CHK.is_emotion(data['value'])
                if len(value_list) > 0:
                    raise serializers.ValidationError("認証サーバ検索文字に使用できない文字が含まれています。")

            if data['config_id'] == 'TARGET_GROUP_LIST':
                targetlist = {}
                value_len = len(data['value'])
                if value_len < 1:
                    raise serializers.ValidationError("対象グループリストは必須項目です")

                value_list = data['value']
                if isinstance(value_list, str):
                    try:
                        value_list = ast.literal_eval(value_list)
                    except Exception as e:
                        raise serializers.ValidationError("対象グループリストの値が不正です val=%s" % (data['value']))

                if not isinstance(value_list, list):
                    raise serializers.ValidationError("対象グループリストの値が不正です val=%s" % (data['value']))

                if len(value_list) <= 0:
                    raise serializers.ValidationError("対象グループリストは必須項目です")

                if len(value_list) > self.TARGET_GROUP_LIST_MAX:
                    raise serializers.ValidationError("対象グループリストは %s 件までです" % (self.TARGET_GROUP_LIST_MAX))

                for i,val in enumerate(value_list):
                    if not isinstance(val, dict):
                        raise serializers.ValidationError("対象グループリストの値が不正です val=%s" % (val))

                    for k, v in val.items():
                        if not k:
                            targetlist[ i * 2 ] = "対象グループリストの値が不正です val=%s" % (val)
                            continue
                        else:
                            # 絵文字チェック
                            value_list = self.EMO_CHK.is_emotion(k)
                            if len(value_list) > 0:
                                targetlist[ i * 2 ] = "対象グループリストの値に使用できない文字が含まれています。"
                                continue

                        if not v:
                            targetlist[ i * 2 + 1 ] = "対象グループリストの値が不正です val=%s" % (val)
                            continue
                        else:
                            # 絵文字チェック
                            value_list = self.EMO_CHK.is_emotion(v)
                            if len(value_list) > 0:
                                targetlist[ i * 2 + 1] = "対象グループリストの値に使用できない文字が含まれています。"
                                continue
                
                if len(targetlist) > 0:
                    raise serializers.ValidationError(targetlist)

            if data['config_id'] == 'AD_LINKAGE_TIMER':
                value_len = len(data['value'])
                values = data['value'].split(',')
                
                # 未入力チェック 
                if not value_len:
                    raise serializers.ValidationError("必須項目が入力されていません。入力してください。")

                # 00~23 チェック
                for x in values:
                    if re.match(self.HOUR_PATTERN, x) is None:
                        raise serializers.ValidationError("00から23の数値を入力してください。")

        return data
Esempio n. 22
0
 def validate(self, data):
     if data.get('password') != data.get('retape_password'):
         raise serializers.ValidationError({'retape_password': '******'})
     del data['retape_password']
     return data
Esempio n. 23
0
	def validate_email(self, value):
		qs  = User.objects.filter(email__iexact = value)
		if qs.exists():
			raise serializers.ValidationError('Email already exist please pick another one')
		return value
Esempio n. 24
0
def is_unique_project_name(name):
    if len(name) <= 6:
        raise serializers.ValidationError('项目名称必须大于6')
Esempio n. 25
0
 def validate(self, data):
     user = authenticate(**data)
     if user and user.is_active:
         return user
     raise serializers.ValidationError("Incorrect Credentials")
Esempio n. 26
0
 def validate_name(self, value):
     if not value.endswith('项目'):
         raise serializers.ValidationError('必须是"项目"结尾')
     return value
Esempio n. 27
0
 def validate_username(self, value):
     if User.objects.filter(username=value).exists():
         raise serializers.ValidationError(
             'This username is already exists!')
     return value
Esempio n. 28
0
 def validate(self, attrs):
     if 'icon' not in attrs['leader'] or 'icon' not in attrs['tester']:
         raise serializers.ValidationError('测试和开发人员必须为icon')
     return attrs
Esempio n. 29
0
 def validate(self, attrs):
     password = attrs.get('password')
     password_confirm = attrs.pop('password_confirmation')
     if password != password_confirm:
         raise serializers.ValidationError('Your password did not match!')
     return attrs
Esempio n. 30
0
 def validate_password(self, password):
     if len(password) < MIN_PASSWORD_LENGHT:
         raise serializers.ValidationError(
             "password must have %s characters at least" %
             MIN_PASSWORD_LENGHT)
     return password