Пример #1
0
class SocketEndpointSerializer(AclMixin, DynamicFieldsMixin, HyperlinkedMixin, MetadataMixin, ModelSerializer):
    hyperlinks = (
        ('self', 'socket-endpoint-endpoint', (
            'instance.name',
            '#name',
        )),
        ('traces', 'socket-endpoint-trace-list', (
            'instance.name',
            '#name',
        ), lambda obj: obj.calls[0]['type'] == 'script'),
        ('history', 'socket-endpoint-history', (
            'instance.name',
            '#name',
        ), lambda obj: obj.calls[0]['type'] == 'channel'),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=SocketEndpoint.objects.all()),
        DjangoValidator()
    ])
    allowed_methods = serializers.SerializerMethodField()

    def get_allowed_methods(self, obj):
        allowed_methods = []
        for call in obj.calls:
            if call['methods'] == ['*']:
                return HTTP_ALL_METHODS
            allowed_methods += call['methods']
        return allowed_methods

    class Meta:
        model = SocketEndpoint
        fields = ('name', 'allowed_methods', 'metadata', 'acl')
Пример #2
0
class SocketSerializer(RevalidateMixin, MetadataMixin, DynamicFieldsMixin, HyperlinkedMixin, ModelSerializer):
    hyperlinks = (
        ('self', 'socket-detail', (
            'instance.name',
            'name',
        )),
        ('update', 'socket-update', (
            'instance.name',
            'name',
        )),
        ('endpoints', 'socket-endpoint-endpoint', (
            'instance.name',
            'name',
        )),
        ('handlers', 'socket-handler-list', (
            'instance.name',
            'name',
        )),
        ('zip_file', 'socket-zip-file', (
            'instance.name',
            'name',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=Socket.objects.all()),
        DjangoValidator()
    ])
    zip_file = FileField(write_only=True)
    zip_file_list = JSONField(validators=[FileListValidator()], default=None, write_only=True)
    config = JSONField(validators=[validate_config], default={})
    install_config = JSONField(write_only=True, default={})
    status = DisplayedChoiceField(Socket.STATUSES.as_choices(), read_only=True)
    status_info = JSONField(read_only=True)
    installed = JSONField(read_only=True)
    files = serializers.SerializerMethodField()
    environment = SlugRelatedField(slug_field='name',
                                   queryset=SocketEnvironment.objects.all(),
                                   default=None, allow_null=True)

    class Meta:
        model = Socket
        fields = ('name', 'description', 'created_at', 'updated_at', 'version',
                  'status', 'status_info', 'install_url', 'metadata', 'config',
                  'zip_file', 'zip_file_list', 'installed', 'files', 'environment',
                  'install_config', )
        read_only_fields = ('install_url', 'version')

    def get_files(self, obj):
        file_list = copy.deepcopy(obj.file_list)

        for val in file_list.values():
            if not val['file'].startswith('<'):
                val['file'] = default_storage.url(val['file'])
        return file_list
Пример #3
0
class InstanceSerializer(RevalidateMixin, DynamicFieldsMixin, MetadataMixin,
                         HyperlinkedMixin, serializers.ModelSerializer):
    hyperlinks = (
        ('self', 'instance-detail', ('name', )),
        ('admins', 'instance-admin-list', ('name', )),
        ('classes', 'klass-list', ('name', )),
        ('codeboxes', 'codebox-list', ('name', )),
        ('runtimes', 'runtime-list', ('name', )),
        ('invitations', 'invitation-list', ('name', )),
        ('api_keys', 'apikey-list', ('name', )),
        ('triggers', 'trigger-list', ('name', )),
        ('webhooks', 'webhook-list', ('name', )),
        ('schedules', 'codebox-schedule-list', ('name', )),
        ('users', 'user-list', ('name', )),
        ('groups', 'group-list', ('name', )),
        ('channels', 'channel-list', ('name', )),
        ('hla_objects', 'hla-objects-list', ('name', )),
        ('batch', 'batch', ('name', )),
        ('templates', 'response-templates-list', ('name', )),
        ('rename', 'instance-rename', ('name', )),
        ('push_notification', 'push-notifications', ('name', )),
        ('backups', 'instance_backups', ('name', )),
        ('restores', 'restores-list', ('name', )),
    )

    name = LowercaseCharField(
        min_length=5,
        validators=[
            UniqueValidator(queryset=Instance.objects.all()),
            DjangoValidator()
        ])
    role = serializers.SerializerMethodField()
    owner = AdminFullSerializer(read_only=True)
    location = serializers.CharField(read_only=True)

    class Meta:
        model = Instance
        fields = ('name', 'description', 'owner', 'created_at', 'updated_at',
                  'role', 'location', 'metadata')

    def get_role(self, obj):
        if hasattr(obj, 'role'):
            return Role.ROLE_CHOICES(obj.role).verbose
        return 'api_key'

    def to_internal_value(self, data):
        reverted_data = super().to_internal_value(data)
        if self.instance is None and reverted_data is not None:
            user = self.context['request'].user
            reverted_data['owner_id'] = user.id
        return reverted_data
Пример #4
0
class WebhookSerializer(RevalidateMixin, DynamicFieldsMixin, HyperlinkedMixin,
                        ModelSerializer):
    hyperlinks = (
        ('self', 'webhook-detail', (
            'instance.name',
            'name',
        )),
        ('run', 'webhook-run', (
            'instance.name',
            'name',
        )),
        ('reset-link', 'webhook-reset-link', (
            'instance.name',
            'name',
        )),
        ('codebox', 'codebox-detail', (
            'instance.name',
            'codebox_id',
        )),
        ('public-link', 'webhook-public-run-with-name',
         ('instance.name', 'public_link', 'name')),
        ('traces', 'webhook-trace-list', (
            'instance.name',
            'name',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=Webhook.objects.all()),
        DjangoValidator()
    ])

    class Meta:
        model = Webhook
        fields = (
            'name',
            'description',
            'codebox',
            'public_link',
            'public',
        )
        extra_kwargs = {
            'public_link': {
                'read_only': True
            },
        }
Пример #5
0
class ChannelSerializer(RevalidateMixin, DynamicFieldsMixin, HyperlinkedMixin,
                        HStoreSerializer):
    hyperlinks = (
        ('self', 'channel-detail', (
            'instance.name',
            'name',
        )),
        ('group', 'group-detail', (
            'instance.name',
            'group_id',
        )),
        ('poll', 'channel-poll', (
            'instance.name',
            'name',
        )),
        ('publish', 'channel-publish', (
            'instance.name',
            'name',
        )),
        ('history', 'change-list', (
            'instance.name',
            'name',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=Channel.objects.all()),
        DjangoValidator()
    ])
    type = DisplayedChoiceField(choices=Channel.TYPES.as_choices(),
                                default=Channel.TYPES.DEFAULT)
    group_permissions = DisplayedChoiceField(
        choices=Channel.PERMISSIONS.as_choices(),
        default=Channel.PERMISSIONS.NONE)
    other_permissions = DisplayedChoiceField(
        choices=Channel.PERMISSIONS.as_choices(),
        default=Channel.PERMISSIONS.NONE)

    class Meta:
        model = Channel
        fields = ('name', 'description', 'type', 'group', 'group_permissions',
                  'other_permissions', 'created_at', 'updated_at',
                  'custom_publish')
Пример #6
0
class DataObjectHighLevelApiSerializer(RevalidateMixin, DynamicFieldsMixin, RemapperMixin, HyperlinkedMixin,
                                       HStoreSerializer):
    hyperlinks = (
        ('self', 'hla-objects-detail', (
            'instance.name',
            'name',
        )),
        ('get', 'hla-objects-get', (
            'instance.name',
            'name',
        )),
        ('post', 'hla-objects-post', (
            'instance.name',
            'name',
        )),
        ('rename', 'hla-objects-rename', (
            'instance.name',
            'name',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=DataObjectHighLevelApi.objects.all()),
        DjangoValidator()
    ])
    query = JSONField(validators=[validate_query],
                      default={})
    klass = SlugRelatedField(slug_field='name', label='class', queryset=Klass.objects.all())
    field_mappings = {'klass': 'class'}

    class Meta:
        model = DataObjectHighLevelApi
        fields = ('name', 'description', 'klass', 'query', 'excluded_fields', 'order_by',
                  'page_size', 'expand')
        extra_kwargs = {
            'excluded_fields': {'validators': [data_field_list_validator]},
            'fields': {'validators': [data_field_list_validator]},
            'expand': {'validators': [data_field_list_validator]},
            'page_size': {'min_value': 0, 'max_value': api_settings.PAGE_SIZE},
        }
Пример #7
0
class SocketEnvironmentSerializer(RevalidateMixin, MetadataMixin, DynamicFieldsMixin, HyperlinkedMixin,
                                  ModelSerializer):
    hyperlinks = (
        ('self', 'socket-environment-detail', (
            'instance.name',
            'name',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=SocketEnvironment.objects.all()),
        DjangoValidator()
    ])
    zip_file = FileField(write_only=True)
    status = DisplayedChoiceField(SocketEnvironment.STATUSES.as_choices(), read_only=True)
    status_info = JSONField(read_only=True)
    checksum = CharField(read_only=True)

    class Meta:
        model = SocketEnvironment
        fields = ('name', 'description', 'created_at', 'updated_at',
                  'status', 'status_info', 'metadata', 'zip_file', 'checksum')
Пример #8
0
class GroupSerializer(DynamicFieldsMixin, HyperlinkedMixin,
                      serializers.ModelSerializer):
    hyperlinks = (
        ('self', 'group-detail', (
            'instance.name',
            'id',
        )),
        ('users', 'group-user-list', (
            'instance.name',
            'id',
        )),
    )

    name = LowercaseCharField(validators=[
        UniqueValidator(queryset=Group.objects.all()),
        DjangoValidator()
    ],
                              allow_null=True,
                              default=None)

    class Meta:
        model = Group
        fields = ('id', 'name', 'label', 'description')
Пример #9
0
class HostingSerializer(DynamicFieldsMixin, HyperlinkedMixin, ModelSerializer):
    hyperlinks = (
        ('self', 'hosting-detail', (
            'instance.name',
            'pk',
        )),
        ('files', 'hosting-file-list', (
            'instance.name',
            'pk',
        )),
        ('set_default', 'hosting-set-default', (
            'instance.name',
            'pk',
        )),
        ('enable_ssl', 'hosting-enable-ssl', (
            'instance.name',
            'pk',
        )),
    )

    name = serializers.CharField(
        max_length=253,
        validators=[
            UniqueValidator(queryset=Hosting.objects.all()),
            HostingNameValidator()
        ])
    domains = serializers.ListField(child=LowercaseCharField(
        max_length=253, validators=[DomainValidator()]), )
    ssl_status = DisplayedChoiceField(
        choices=Hosting.SSL_STATUSES.as_choices(), read_only=True)

    class Meta:
        model = Hosting
        read_only_fields = ('is_default', )
        fields = ('id', 'name', 'is_default', 'description', 'created_at',
                  'updated_at', 'domains', 'is_active', 'ssl_status')

    def validate_domains(self, value):
        value_set = set(value)
        only_domains = [
            v for v in value_set if re.match(VALID_DOMAIN_REGEX, v)
        ]
        # Only 1 domain per hosting allowed so that we can process SSL properly
        if len(only_domains) > 1:
            raise OnlyOneDomainAllowed()

        # this checks the global domains;
        if Instance.objects.exclude(pk=get_current_instance().pk).filter(
                domains__overlap=only_domains).exists():
            raise DomainAlreadyUsed()

        # prevent for creating hosting with the same domain;
        # but allow to update the same object with the same domains;
        validate_queryset = Hosting.objects.all()
        # update case; if empty - create case;
        current_hosting = self.instance
        if current_hosting:
            validate_queryset = validate_queryset.exclude(
                pk=current_hosting.pk)

        # use a all values here - this will check if no two hosting objects exists with the same instance name
        # and suffix combination;
        if validate_queryset.filter(domains__overlap=list(value_set)).exists():
            raise DomainAlreadyUsed()

        return list(value_set)

    def validate(self, data):
        if self.instance and self.instance.is_locked:
            raise HostingLocked()
        return super().validate(data)

    def to_internal_value(self, data):
        reverted_data = super().to_internal_value(data)
        # Automatically add name to domains
        if reverted_data:
            if 'name' in reverted_data:
                name = reverted_data['name']
            else:
                name = self.instance.name

            if 'domains' in reverted_data:
                domains = reverted_data['domains']
            else:
                domains = self.instance

            if isinstance(domains, list):
                if name not in domains:
                    domains.append(name)
            else:
                reverted_data['domains'] = [name]
        return reverted_data
Пример #10
0
class BatchRequestSerializer(serializers.Serializer):
    method = serializers.ChoiceField(choices=('GET', 'POST', 'PUT', 'PATCH', 'DELETE'))
    path = LowercaseCharField(max_length=8192, validators=[PathValidator()])
    body = JSONField(default={}, validators=[validate_batch_body])