Пример #1
0
 def check_read_only(self):
     if self.request is None:
         try:
             self.request = get_current_request()
         except RequestNotFound:
             return False
     if hasattr(self.request, '_db_write_enabled') and not self.request._db_write_enabled:
         raise Unauthorized('Adding content not permited')
     # Add the new tid
     if self._manager._storage._read_only:
         raise ReadOnlyError()
Пример #2
0
 def check_read_only(self):
     if self.request is None:
         self.request = get_current_request()
     if hasattr(self.request,
                '_db_write_enabled') and not self.request._db_write_enabled:
         raise Unauthorized('Adding content not permited')
Пример #3
0
    async def set_schema(
        self,
        schema: Type[Interface],
        obj: IResource,
        data: Dict[str, Any],
        errors: List[Dict[str, Any]],
        validate_all: bool = False,
        behavior: bool = False,
    ):
        write_permissions = merged_tagged_value_dict(schema,
                                                     write_permission.key)
        changed = False
        for name, field in get_fields(schema).items():

            if name in RESERVED_ATTRS:
                continue

            if field.readonly:
                continue

            if behavior:
                found = False
                if data.get(schema.__identifier__):
                    sdata = data[schema.__identifier__]
                    data_value = sdata[name] if name in sdata else None
                    found = True if name in sdata else False
            else:
                data_value = data[name] if name in data else None
                found = True if name in data else False
            if found:

                if not self.check_permission(write_permissions.get(name)):
                    raise Unauthorized("Write permission not allowed")

                try:
                    field = field.bind(obj)
                    value = await self.get_value(field, obj, data_value)
                except ValueError as e:
                    errors.append({
                        "message": "Value error",
                        "field": name,
                        "error": e
                    })
                except ValidationError as e:
                    errors.append(e.json())
                except ValueDeserializationError as e:
                    errors.append({
                        "message": e.message,
                        "field": name,
                        "error": e
                    })
                except Invalid as e:
                    errors.append({
                        "message": e.args[0],
                        "field": name,
                        "error": e
                    })
                else:
                    # record object changes for potential future conflict resolution
                    try:
                        await apply_coroutine(field.set, obj, value)
                        changed = True
                    except ValidationError as e:
                        errors.append(e.json())
                    except ValueDeserializationError as e:
                        errors.append({
                            "message": e.message,
                            "field": name,
                            "error": e
                        })
                    except AttributeError:
                        logger.warning(
                            f"AttributeError setting data on field {name}",
                            exc_info=True)
                    except Exception:
                        logger.warning(
                            f"Unhandled error setting data on field, {schema} {name}",
                            exc_info=True)
                        errors.append({
                            "message":
                            "Unhandled exception",
                            "field":
                            name,
                            "error":
                            ValueDeserializationError(field, value,
                                                      "Unhandled error"),
                        })
            else:
                if validate_all and field.required and getattr(
                        obj, name, None) is None:
                    errors.append({
                        "message": "Required parameter",
                        "field": name,
                        "error": ValueError("Required parameter"),
                    })

        for error in await validate_invariants(schema, obj):
            if isinstance(error, ValidationError):
                errors.append({
                    "message": error.doc(),
                    "value": error.value,
                    "field": error.field_name,
                    "error": error.errors,
                })
            else:
                if len(getattr(error, "args", [])) > 0 and isinstance(
                        error.args[0], str):
                    message = error.args[0]
                else:
                    message = error.__doc__
                errors.append({"message": message, "error": error})

        if changed:
            obj.register()
Пример #4
0
    async def set_schema(self,
                         schema,
                         obj,
                         data,
                         errors,
                         validate_all=False,
                         behavior=False):
        write_permissions = merged_tagged_value_dict(schema,
                                                     write_permission.key)

        for name, field in get_fields(schema).items():
            if name in RESERVED_ATTRS:
                continue

            if field.readonly:
                continue

            if behavior:
                found = False
                if schema.__identifier__ in data:
                    sdata = data[schema.__identifier__]
                    data_value = sdata[name] if name in sdata else None
                    found = True if name in sdata else False
            else:
                data_value = data[name] if name in data else None
                found = True if name in data else False
            if found:

                if not self.check_permission(write_permissions.get(name)):
                    raise Unauthorized('Write permission not allowed')

                try:
                    field = field.bind(obj)
                    value = await self.get_value(field, obj, data_value)
                except ValueError as e:
                    errors.append({
                        'message': 'Value error',
                        'field': name,
                        'error': e
                    })
                except ValidationError as e:
                    errors.append({
                        'message': e.doc(),
                        'field': name,
                        'error': e
                    })
                except ValueDeserializationError as e:
                    errors.append({
                        'message': e.message,
                        'field': name,
                        'error': e
                    })
                except Invalid as e:
                    errors.append({
                        'message': e.args[0],
                        'field': name,
                        'error': e
                    })
                else:
                    # record object changes for potential future conflict resolution
                    try:
                        await notify(BeforeFieldModifiedEvent(field, value))
                        await apply_coroutine(field.set, obj, value)
                    except ValidationError as e:
                        errors.append({
                            'message': e.doc(),
                            'field': name,
                            'error': e
                        })
                    except ValueDeserializationError as e:
                        errors.append({
                            'message': e.message,
                            'field': name,
                            'error': e
                        })
                    except AttributeError:
                        logger.warning(
                            f'AttributeError setting data on field {name}',
                            exc_info=True)
                    except Exception:
                        if not isinstance(getattr(type(obj), name, None),
                                          property):
                            # we can not set data on properties
                            logger.warning(
                                'Error setting data on field, falling back to setattr',
                                exc_info=True)
                            setattr(obj, name, value)
                        else:
                            logger.warning('Error setting data on field',
                                           exc_info=True)
            else:
                if validate_all and field.required and getattr(
                        obj, name, None) is None:
                    errors.append({
                        'message': 'Required parameter',
                        'field': name,
                        'error': ValueError('Required parameter')
                    })

        if validate_all:
            invariant_errors = []
            try:
                schema.validateInvariants(object, invariant_errors)
            except Invalid:
                # Just collect errors
                pass
            validation = [(None, e) for e in invariant_errors]

            if len(validation):
                for error in validation:
                    errors.append({
                        'message': error[1].doc(),
                        'field': error[0],
                        'error': error
                    })