Ejemplo n.º 1
0
class IContentTypeDirective(Interface):

    portal_type = configuration_fields.MessageID(title=_('Portal type'),
                                                 description='',
                                                 required=True)

    class_ = configuration_fields.GlobalObject(title=_('Class'),
                                               description='',
                                               required=False)

    schema = configuration_fields.GlobalInterface(title='',
                                                  description='',
                                                  required=True)

    behaviors = configuration_fields.Tokens(
        title='',
        description='',
        value_type=configuration_fields.GlobalInterface(),
        required=False)

    allowed_types = configuration_fields.Tokens(
        title='',
        description='',
        value_type=configuration_fields.MessageID(),
        required=False)

    add_permission = configuration_fields.MessageID(
        title=_('Add permission'), default=DEFAULT_ADD_PERMISSION)
Ejemplo n.º 2
0
class IAddOn(Interface):

    name = configuration_fields.PythonIdentifier(title=_('Name of the addon'),
                                                 description='',
                                                 required=True)

    title = configuration_fields.MessageID(title=_('Name of the addon'),
                                           description='',
                                           required=True)

    handler = configuration_fields.GlobalObject(
        title=_('Handler for the addon'), description='', required=True)
Ejemplo n.º 3
0
    async def initialize(self, app=None):
        # loop
        self.app = app
        while True:
            got_obj = False
            try:
                priority, view = await self._queue.get()
                got_obj = True
                if view.request.conn.transaction_manager is None:
                    # Connection was closed
                    # Open DB
                    db = view.request.application[view.request._db_id]
                    if SHARED_CONNECTION:
                        view.request.conn = db.conn
                    else:
                        # Create a new conection
                        view.request.conn = db.open()
                    view.context = view.request.conn.get(view.context._p_oid)

                txn = view.request.conn.transaction_manager.begin(view.request)
                try:
                    view_result = await view()
                    if isinstance(view_result, ErrorResponse):
                        await sync(view.request)(txn.abort)
                    elif isinstance(view_result, UnauthorizedResponse):
                        await sync(view.request)(txn.abort)
                    else:
                        await sync(view.request)(txn.commit)
                except Unauthorized:
                    await sync(view.request)(txn.abort)
                    view_result = UnauthorizedResponse(
                        _('Not authorized to render operation'))
                except Exception as e:
                    logger.error("Exception on writing execution", exc_info=e)
                    await sync(view.request)(txn.abort)
                    view_result = ErrorResponse(
                        'ServiceError', _('Error on execution of operation'))
            except KeyboardInterrupt or MemoryError or SystemExit or asyncio.CancelledError:
                self._exceptions = True
                raise
            except Exception as e:  # noqa
                self._exceptions = True
                logger.error('Worker call failed', exc_info=e)
            finally:
                if got_obj:
                    self._queue.task_done()
Ejemplo n.º 4
0
class IResourceDirectory(Interface):

    name = configuration_fields.MessageID(
        title=_('Name where is going to be published'),
        description='',
        required=True)

    directory = Path(title='The name of the directory',
                     description='Publish at /static the directory',
                     required=True)
Ejemplo n.º 5
0
    def _validate(self, value):
        if self.allowed_mime_types\
                and value.mimeType not in self.allowed_mime_types:
            raise WrongType(value, self.allowed_mime_types)

        if self.max_length is not None and len(value.raw) > self.max_length:
            raise Invalid(_(
                'msg_text_too_long',
                default=u'Text is too long. (Maximum ${max} characters.)',
                mapping={'max': self.max_length}
            ))

        if not self.constraint(value):
            raise ConstraintNotSatisfied(value)
Ejemplo n.º 6
0
def generate_unauthorized_response(e, request):
    # We may need to check the roles of the users to show the real error
    eid = uuid.uuid4().hex
    message = _('Not authorized to render operation') + ' ' + eid
    user = get_authenticated_user_id(request)
    extra = {
        'r': _url(request),
        'u': user
    }
    logger.error(
        message,
        exc_info=e,
        extra=extra)
    return UnauthorizedResponse(message)
Ejemplo n.º 7
0
def generate_error_response(e, request, error, status=400):
    # We may need to check the roles of the users to show the real error
    eid = uuid.uuid4().hex
    message = _('Error on execution of view') + ' ' + eid
    user = get_authenticated_user_id(request)
    extra = {
        'r': _url(request),
        'u': user
    }
    logger.error(
        message,
        exc_info=e,
        extra=extra)

    return ErrorResponse(
        error,
        message,
        status
    )
Ejemplo n.º 8
0
    async def __call__(self):
        """To create a content."""
        data = await self.get_data()
        type_ = data.get('@type', None)
        id_ = data.get('id', None)
        behaviors = data.get('@behaviors', None)

        if not type_:
            return ErrorResponse('RequiredParam',
                                 _("Property '@type' is required"))

        # Generate a temporary id if the id is not given
        if not id_:
            new_id = None
        else:
            new_id = id_

        user = get_authenticated_user_id(self.request)
        # Create object
        try:
            obj = create_content_in_container(self.context,
                                              type_,
                                              new_id,
                                              id=new_id,
                                              creators=(user, ),
                                              contributors=(user, ))
        except PreconditionFailed as e:
            return ErrorResponse('PreconditionFailed', str(e), status=412)
        except ConflictIdOnContainer as e:
            return ErrorResponse('ConflictId', str(e), status=409)
        except ValueError as e:
            return ErrorResponse('CreatingObject', str(e), status=400)

        for behavior in behaviors or ():
            obj.add_behavior(behavior)

        # Update fields
        deserializer = queryMultiAdapter((obj, self.request),
                                         IResourceDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse('DeserializationError',
                                 'Cannot deserialize type {}'.format(
                                     obj.portal_type),
                                 status=501)

        try:
            await deserializer(data, validate_all=True)
        except DeserializationError as e:
            return ErrorResponse('DeserializationError',
                                 str(e),
                                 exc=e,
                                 status=400)

        # Local Roles assign owner as the creator user
        roleperm = IPrincipalRoleManager(obj)
        roleperm.assignRoleToPrincipal('plone.Owner', user)

        await notify(ObjectFinallyCreatedEvent(obj))

        absolute_url = queryMultiAdapter((obj, self.request), IAbsoluteURL)

        headers = {
            'Access-Control-Expose-Headers': 'Location',
            'Location': absolute_url()
        }

        serializer = queryMultiAdapter((obj, self.request),
                                       IResourceSerializeToJson)
        return Response(response=serializer(), headers=headers, status=201)
Ejemplo n.º 9
0
    async def __call__(self):
        """To create a content."""
        data = await self.get_data()
        type_ = data.get('@type', None)
        id_ = data.get('id', None)
        behaviors = data.get('@behaviors', None)

        if '__acl__' in data:
            # we don't allow to change the permisions on this patch
            del data['__acl__']

        if not type_:
            return ErrorResponse(
                'RequiredParam',
                _("Property '@type' is required"))

        # Generate a temporary id if the id is not given
        if not id_:
            new_id = None
        else:
            new_id = id_

        user = get_authenticated_user_id(self.request)
        # Create object
        try:
            obj = create_content_in_container(
                self.context, type_, new_id, id=new_id, creators=(user,),
                contributors=(user,))
        except PreconditionFailed as e:
            return ErrorResponse(
                'PreconditionFailed',
                str(e),
                status=412)
        except ConflictIdOnContainer as e:
            return ErrorResponse(
                'ConflictId',
                str(e),
                status=409)
        except ValueError as e:
            return ErrorResponse(
                'CreatingObject',
                str(e),
                status=400)

        for behavior in behaviors or ():
            obj.add_behavior(behavior)

        # Update fields
        deserializer = queryMultiAdapter((obj, self.request),
                                         IResourceDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse(
                'DeserializationError',
                'Cannot deserialize type {}'.format(obj.portal_type),
                status=501)

        try:
            await deserializer(data, validate_all=True)
        except DeserializationError as e:
            return ErrorResponse(
                'DeserializationError',
                str(e),
                exc=e,
                status=400)

        # Local Roles assign owner as the creator user
        roleperm = IPrincipalRoleManager(obj)
        roleperm.assign_role_to_principal(
            'plone.Owner',
            user)

        await notify(ObjectFinallyCreatedEvent(obj, data))

        absolute_url = queryMultiAdapter((obj, self.request), IAbsoluteURL)

        headers = {
            'Access-Control-Expose-Headers': 'Location',
            'Location': absolute_url()
        }

        serializer = queryMultiAdapter(
            (obj, self.request),
            IResourceSerializeToJson
        )
        return Response(response=serializer(), headers=headers, status=201)