Beispiel #1
0
    def validate(self, attrs):
        """
        Validate url if we are adding a media uri instead of a media file
        """
        value = attrs.get('data_value')
        data_type = attrs.get('data_type')
        data_file = attrs.get('data_file')

        if not ('project' in attrs or 'xform' in attrs or 'instance' in attrs):
            raise serializers.ValidationError({
                'missing_field':
                _(u"`xform` or `project` or `instance`"
                  "field is required.")
            })

        if data_type == 'media' and data_file is None:
            try:
                URLValidator()(value)
            except ValidationError:
                parts = value.split()
                if len(parts) < 3:
                    raise serializers.ValidationError({
                        'data_value':
                        _(u"Expecting 'xform [xform id] [media name]' "
                          "or 'dataview [dataview id] [media name]' "
                          "or a valid URL.")
                    })
                obj = get_linked_object(parts)
                if obj:
                    xform = obj.xform if isinstance(obj, DataView) else obj
                    request = self.context['request']
                    user_has_role = ManagerRole.user_has_role
                    has_perm = user_has_role(request.user, xform) or \
                        user_has_role(request.user, obj.project)
                    if not has_perm:
                        raise serializers.ValidationError({
                            'data_value':
                            _(u"User has no permission to "
                              "the dataview.")
                        })
                else:
                    raise serializers.ValidationError(
                        {'data_value': _(u"Invalid url '%s'." % value)})
            else:
                # check if we have a value for the filename.
                if not os.path.basename(urlparse(value).path):
                    raise serializers.ValidationError({
                        'data_value':
                        _(u"Cannot get filename from URL %s. URL should "
                          u"include the filename e.g "
                          u"http://example.com/data.csv" % value)
                    })

        if data_type == XFORM_META_PERMS:
            perms = value.split('|')
            if len(perms) != 2 or not set(perms).issubset(set(ROLES.keys())):
                raise serializers.ValidationError(
                    _(u"Format 'role'|'role' or Invalid role"))

        return attrs