def test_type_name_condition(dummy_request):
    login(dummy_request)
    ob = create_content()
    assert type_name.condition(ob, dummy_request, ObjectAddedEvent(ob),
                               {'type_name': 'Item'})

    assert not type_name.condition(ob, dummy_request, ObjectAddedEvent(ob),
                                   {'type_name': 'foobar'})
def test_user_condition(dummy_request):
    login(dummy_request)
    ob = create_content()
    assert user.condition(ob, dummy_request, ObjectAddedEvent(ob),
                          {'user': '******'})

    assert not user.condition(ob, dummy_request, ObjectAddedEvent(ob),
                              {'user': '******'})
Beispiel #3
0
    async def generate_test_data(self, db):
        # don't slow us down with transactions
        db._db._storage._transaction_strategy = 'none'

        tm = db.get_transaction_manager()
        tm.request = self.request
        await tm.begin(self.request)
        container = await db.async_get('testdata')
        if container is None:
            container = await create_content(
                'Container', id='testdata', title='Test Data')
            container.__name__ = 'testdata'
            await db.async_set('testdata', container)
            await container.install()
            self.request._container_id = container.__name__
            # Local Roles assign owner as the creator user
            roleperm = IPrincipalRoleManager(container)
            roleperm.assign_role_to_principal('guillotina.Owner', 'root')

            await notify(ObjectAddedEvent(container, db, container.__name__))
            await tm.commit()
            await tm.begin(self.request)

        api = WikipediaAPI()
        folder_count = 0
        async for page_data in api.iter_pages():
            await self.import_folder(api, tm, container, page_data)
            folder_count += 1
            if folder_count >= self.arguments.per_node:
                break
Beispiel #4
0
async def run(token_data, payload):
    # Payload : {
    #   'new_password': '******',
    # }
    container = get_current_container()
    user_folders = await container.async_get("users")

    data = {}

    valid_data = ["username", "email", "name", "password", "properties"]

    for key in valid_data:
        if key in token_data:
            data[key] = token_data[key]

    user = await create_content_in_container(
        user_folders,
        "User",
        token_data.get("username", token_data.get("id")),
        creators=(token_data.get("username", token_data.get("id")),),
        check_security=False,
        **data,
    )
    user.user_roles = ["guillotina.Member"]
    await notify(ObjectAddedEvent(user))

    jwt_token, data = authenticate_user(user.id, timeout=app_settings["jwt"]["token_expiration"])
    await notify(UserLogin(user, jwt_token))

    return {"exp": data["exp"], "token": jwt_token}
Beispiel #5
0
async def runit(type_name):
    print(f'Test content creation with {type_name}')
    request = get_current_request()
    txn = mocks.MockTransaction()
    container = await create_content(type_name, id='container')
    container._p_jar = txn
    start = time.time()
    for _ in range(ITERATIONS):
        ob = await create_content(type_name, id='foobar')
        ob._p_jar = txn
        await notify(BeforeObjectAddedEvent(ob, container, 'foobar'))
        deserializer = get_multi_adapter((ob, request),
                                         IResourceDeserializeFromJson)
        data = {
            'title': 'Foobar',
            'guillotina.behaviors.dublincore.IDublinCore': {
                'tags': ['foo', 'bar']
            },
            'measures.configuration.ITestBehavior1': {
                'foobar': '123'
            },
            'measures.configuration.ITestBehavior2': {
                'foobar': '123'
            },
            'measures.configuration.ITestBehavior3': {
                'foobar': '123'
            }
        }
        await deserializer(data, validate_all=True)
        await notify(ObjectAddedEvent(ob, container, 'foobar', payload=data))
    end = time.time()
    print(f'Done with {ITERATIONS} in {end - start} seconds')
Beispiel #6
0
async def create_container(
    parent: IDatabase,
    container_id: str,
    container_type: str = "Container",
    owner_id: Optional[str] = None,
    emit_events: bool = True,
    **data,
):
    container = await create_content(container_type, id=container_id, **data)

    # Special case we don't want the parent pointer
    container.__name__ = container_id

    task_vars.container.set(container)
    await parent.async_set(container_id, container)
    await container.install()

    # Local Roles assign owner as the creator user
    if owner_id is not None:
        roleperm = IPrincipalRoleManager(container)
        roleperm.assign_role_to_principal("guillotina.Owner", owner_id)

    if emit_events:
        await notify(
            ObjectAddedEvent(container,
                             parent,
                             container.__name__,
                             payload={
                                 "id": container.id,
                                 **data
                             }))
    task_vars.container.set(container)
    return container
Beispiel #7
0
    async def __call__(self):
        data = await self.request.json()
        if '@type' not in data or data['@type'] not in app_settings[
                'container_types']:
            raise HTTPNotFound(
                content={
                    'message': 'can not create this type %s' % data['@type']
                })

        if 'id' not in data:
            raise HTTPPreconditionFailed(content={'message': 'We need an id'})

        if not data.get('title'):
            data['title'] = data['id']

        if 'description' not in data:
            data['description'] = ''

        value = await self.context.async_contains(data['id'])

        if value:
            # Already exist
            raise HTTPConflict(
                content={'message': 'Container with id already exists'})

        container = await create_content(data['@type'],
                                         id=data['id'],
                                         title=data['title'],
                                         description=data['description'])

        # Special case we don't want the parent pointer
        container.__name__ = data['id']

        await self.context.async_set(data['id'], container)
        await container.install()

        self.request._container_id = container.__name__
        self.request.container = container

        user = get_authenticated_user_id(self.request)

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

        await notify(
            ObjectAddedEvent(container,
                             self.context,
                             container.__name__,
                             payload=data))

        resp = {
            '@type': data['@type'],
            'id': data['id'],
            'title': data['title']
        }
        headers = {'Location': posixpath.join(self.request.path, data['id'])}

        return Response(content=resp, headers=headers)
Beispiel #8
0
    async def __call__(self):
        data = await self.request.json()
        if '@type' not in data or data['@type'] != 'Container':
            return ErrorResponse('NotAllowed',
                                 'can not create this type %s' % data['@type'],
                                 status=401)

        if 'id' not in data:
            return ErrorResponse('NotAllowed', 'We need an id', status=401)

        if not data.get('title'):
            data['title'] = data['id']

        if 'description' not in data:
            data['description'] = ''

        value = await self.context.async_contains(data['id'])

        if value:
            # Already exist
            return ErrorResponse('ConflictId',
                                 'Container with id already exists',
                                 status=409)

        container = await create_content('Container',
                                         id=data['id'],
                                         title=data['title'],
                                         description=data['description'])

        # Special case we don't want the parent pointer
        container.__name__ = data['id']

        await self.context.async_set(data['id'], container)
        await container.install()

        self.request._container_id = container.__name__
        self.request.container = container

        user = get_authenticated_user_id(self.request)

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

        await notify(
            ObjectAddedEvent(container,
                             self.context,
                             container.__name__,
                             payload=data))

        resp = {'@type': 'Container', 'id': data['id'], 'title': data['title']}
        headers = {'Location': self.request.path + data['id']}

        return Response(response=resp, headers=headers)
async def test_executes_actions(dummy_guillotina, cr_executor):
    ob = create_content()
    executor = cr_executor(ob, None, ObjectAddedEvent(ob), [{
        'conditions': [{
            'condition_type': 'event',
            'configuration': {
                'event_name': 'add'
            }
        }]
    }])

    assert len(await executor.get_matching_rules()) == 1
Beispiel #10
0
    async def __call__(self):
        data = await self.request.json()
        if '@type' not in data and data['@type'] != 'Site':
            return ErrorResponse('NotAllowed',
                                 'can not create this type %s' % data['@type'],
                                 status=401)

        if 'title' not in data and not data['title']:
            return ErrorResponse('NotAllowed', 'We need a title', status=401)

        if 'id' not in data:
            return ErrorResponse('NotAllowed', 'We need an id', status=401)

        if 'description' not in data:
            data['description'] = ''

        value = await self.context.async_contains(data['id'])

        if value:
            # Already exist
            return ErrorResponse('NotAllowed', 'Duplicate id', status=401)

        site = await create_content('Site',
                                    id=data['id'],
                                    title=data['title'],
                                    description=data['description'])

        # Special case we don't want the parent pointer
        site.__name__ = data['id']

        await self.context.async_set(data['id'], site)
        await site.install()

        self.request._site_id = site.__name__

        user = get_authenticated_user_id(self.request)

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

        await notify(ObjectAddedEvent(site, self.context, site.__name__))

        resp = {'@type': 'Site', 'id': data['id'], 'title': data['title']}
        headers = {'Location': self.request.path + data['id']}

        return Response(response=resp, headers=headers)
Beispiel #11
0
    async def generate_test_data(self, db):
        tm = db.get_transaction_manager()
        task_vars.db.set(db)
        tm = db.get_transaction_manager()
        txn = await tm.begin()

        container = await db.async_get(self.arguments.container)
        if container is None:
            container = await create_content("Container",
                                             id=self.arguments.container,
                                             title="Test Data")
            container.__name__ = self.arguments.container
            await db.async_set(self.arguments.container, container)
            await container.install()
            # Local Roles assign owner as the creator user
            roleperm = IPrincipalRoleManager(container)
            roleperm.assign_role_to_principal("guillotina.Owner", "root")

            await notify(ObjectAddedEvent(container, db, container.__name__))
            try:
                await tm.commit(txn=txn)
            except ConflictIdOnContainer:
                # ignore id conflicts
                await tm.abort(txn=txn)
            txn = await tm.begin()

        task_vars.registry.set(None)
        task_vars.container.set(container)

        api = WikipediaAPI()
        folder_count = 0
        async for page_data in api.iter_pages():
            await self.import_folder(api, tm, txn, container, page_data)
            folder_count += 1
            if folder_count >= self.arguments.per_node:
                break

        try:
            await tm.commit(txn=txn)
        except ConflictIdOnContainer:
            # ignore id conflicts
            await tm.abort(txn=txn)
        api.close()
Beispiel #12
0
async def runit(type_name):
    print(f"Test content creation with {type_name}")
    request = get_current_request()
    txn = mocks.MockTransaction()
    container = await create_content(type_name, id="container")
    container.__txn__ = txn
    start = time.time()
    for _ in range(ITERATIONS):
        ob = await create_content(type_name, id="foobar")
        ob.__txn__ = txn
        await notify(BeforeObjectAddedEvent(ob, container, "foobar"))
        deserializer = get_multi_adapter((ob, request), IResourceDeserializeFromJson)
        data = {
            "title": "Foobar",
            "guillotina.behaviors.dublincore.IDublinCore": {"tags": ["foo", "bar"]},
            "measures.configuration.ITestBehavior1": {"foobar": "123"},
            "measures.configuration.ITestBehavior2": {"foobar": "123"},
            "measures.configuration.ITestBehavior3": {"foobar": "123"},
        }
        await deserializer(data, validate_all=True)
        await notify(ObjectAddedEvent(ob, container, "foobar", payload=data))
    end = time.time()
    print(f"Done with {ITERATIONS} in {end - start} seconds")
Beispiel #13
0
    async def generate_test_data(self, db):
        tm = self.request._tm = db.get_transaction_manager()
        self.request._db_id = db.id
        tm = db.get_transaction_manager()
        self.request._txn = txn = await tm.begin(self.request)

        container = await db.async_get(self.arguments.container)
        if container is None:
            container = await create_content('Container',
                                             id=self.arguments.container,
                                             title='Test Data')
            container.__name__ = self.arguments.container
            await db.async_set(self.arguments.container, container)
            await container.install()
            self.request._container_id = container.__name__
            # Local Roles assign owner as the creator user
            roleperm = IPrincipalRoleManager(container)
            roleperm.assign_role_to_principal('guillotina.Owner', 'root')

            await notify(ObjectAddedEvent(container, db, container.__name__))
            await tm.commit(txn=txn)
            txn = await tm.begin(self.request)

        self.request.container = container
        self.request._container_id = container.id

        api = WikipediaAPI()
        folder_count = 0
        async for page_data in api.iter_pages():
            await self.import_folder(api, tm, txn, container, page_data)
            folder_count += 1
            if folder_count >= self.arguments.per_node:
                break

        await tm.commit(txn=txn)
        api.close()
Beispiel #14
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:
            if not valid_id(id_):
                return ErrorResponse('PreconditionFailed',
                                     str('Invalid id'),
                                     status=412)
            new_id = id_

        user = get_authenticated_user_id(self.request)

        # Create object
        try:
            obj = await create_content_in_container(self.context,
                                                    type_,
                                                    new_id,
                                                    id=new_id,
                                                    creators=(user, ),
                                                    contributors=(user, ))
        except (PreconditionFailed, NotAllowedContentType) 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.type_name),
                                 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
        get_owner = getUtility(IGetOwner)
        roleperm = IPrincipalRoleManager(obj)
        roleperm.assign_role_to_principal('guillotina.Owner', await
                                          get_owner(obj, user))

        await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data))

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

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

        serializer = queryMultiAdapter((obj, self.request),
                                       IResourceSerializeToJson)
        response = await serializer()
        return Response(response=response, headers=headers, status=201)
Beispiel #15
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_:
            raise ErrorResponse('RequiredParam',
                                _("Property '@type' is required"),
                                reason=error_reasons.REQUIRED_PARAM_MISSING,
                                status=412)

        # Generate a temporary id if the id is not given
        new_id = None
        if not id_:
            generator = query_adapter(self.request, IIDGenerator)
            if generator is not None:
                new_id = generator(data)
        else:
            if not isinstance(id_, str) or not valid_id(id_):
                raise ErrorResponse('PreconditionFailed',
                                    str('Invalid id'),
                                    status=412,
                                    reason=error_reasons.INVALID_ID)
            new_id = id_

        user = get_authenticated_user_id(self.request)

        options = {'creators': (user, ), 'contributors': (user, )}
        if 'uid' in data:
            options['_p_oid'] = data.pop('uid')

        # Create object
        try:
            obj = await create_content_in_container(self.context, type_,
                                                    new_id, **options)
        except ValueError as e:
            return ErrorResponse('CreatingObject', str(e), status=412)

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

        # Update fields
        deserializer = query_multi_adapter((obj, self.request),
                                           IResourceDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse('DeserializationError',
                                 'Cannot deserialize type {}'.format(
                                     obj.type_name),
                                 status=412,
                                 reason=error_reasons.DESERIALIZATION_FAILED)

        await deserializer(data, validate_all=True, create=True)

        # Local Roles assign owner as the creator user
        get_owner = get_utility(IGetOwner)
        roleperm = IPrincipalRoleManager(obj)
        owner = await get_owner(obj, user)
        if owner is not None:
            roleperm.assign_role_to_principal('guillotina.Owner', owner)

        data['id'] = obj.id
        await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data))

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

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

        serializer = query_multi_adapter((obj, self.request),
                                         IResourceSerializeToJsonSummary)
        response = await serializer()
        return Response(content=response, status=201, headers=headers)
def test_event_condition_matches(dummy_guillotina):
    ob = create_content()
    assert event.condition(ob, None, ObjectAddedEvent(ob),
                           {'event_name': 'add'})
Beispiel #17
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_:
            raise ErrorResponse(
                "RequiredParam",
                _("Property '@type' is required"),
                reason=error_reasons.REQUIRED_PARAM_MISSING,
                status=412,
            )

        id_checker = get_adapter(self.context, IIDChecker)
        # Generate a temporary id if the id is not given
        new_id = None
        if not id_:
            generator = query_adapter(self.request, IIDGenerator)
            if generator is not None:
                new_id = await apply_coroutine(generator, data)
                if isinstance(new_id, str) and not await id_checker(new_id, type_):
                    raise ErrorResponse(
                        "PreconditionFailed",
                        "Invalid id: {}".format(new_id),
                        status=412,
                        reason=error_reasons.INVALID_ID,
                    )
        else:
            if not isinstance(id_, str) or not await id_checker(id_, type_):
                raise ErrorResponse(
                    "PreconditionFailed",
                    "Invalid id: {}".format(id_),
                    status=412,
                    reason=error_reasons.INVALID_ID,
                )
            new_id = id_

        user = get_authenticated_user_id()

        options = {"creators": (user,), "contributors": (user,)}
        if "uid" in data:
            options["__uuid__"] = data.pop("uid")

        # Create object
        try:
            obj = await create_content_in_container(
                self.context, type_, new_id, check_constraints=True, **options
            )
        except ValueError as e:
            return ErrorResponse("CreatingObject", str(e), status=412)

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

        # Update fields
        deserializer = query_multi_adapter((obj, self.request), IResourceDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse(
                "DeserializationError",
                "Cannot deserialize type {}".format(obj.type_name),
                status=412,
                reason=error_reasons.DESERIALIZATION_FAILED,
            )

        await deserializer(data, validate_all=True, create=True)

        # Local Roles assign owner as the creator user
        get_owner = IGetOwner(obj)
        roleperm = IPrincipalRoleManager(obj)
        owner = await get_owner(user)
        if owner is not None:
            roleperm.assign_role_to_principal("guillotina.Owner", owner)

        data["id"] = obj.id
        await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data))

        headers = {"Access-Control-Expose-Headers": "Location", "Location": get_object_url(obj, self.request)}

        serializer = query_multi_adapter((obj, self.request), IResourceSerializeToJsonSummary)
        response = await serializer()
        return Response(content=response, status=201, headers=headers)
Beispiel #18
0
    async def __call__(self):
        data = await self.request.json()
        if '@type' not in data or data['@type'] not in app_settings['container_types']:
            raise HTTPNotFound(content={
                'message': 'can not create this type %s' % data['@type']
            })

        if 'id' not in data:
            raise HTTPPreconditionFailed(content={
                'message': 'We need an id'
            })

        if not data.get('title'):
            data['title'] = data['id']

        if 'description' not in data:
            data['description'] = ''

        value = await self.context.async_contains(data['id'])

        if value:
            # Already exist
            raise HTTPConflict(content={
                'message': 'Container with id already exists'
            })

        container = await create_content(
            data['@type'],
            id=data['id'],
            title=data['title'],
            description=data['description'])

        # Special case we don't want the parent pointer
        container.__name__ = data['id']

        await self.context.async_set(data['id'], container)
        await container.install()

        self.request._container_id = container.__name__
        self.request.container = container

        user = get_authenticated_user_id(self.request)

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

        annotations_container = get_adapter(container, IAnnotations)
        self.request.container_settings = await annotations_container.async_get(REGISTRY_DATA_KEY)

        for addon in data.get('@addons') or []:
            if addon not in app_settings['available_addons']:
                return ErrorResponse(
                    'RequiredParam',
                    "Property '@addons' must refer to a valid addon",
                    status=412, reason=error_reasons.INVALID_ID)
            await addons.install(container, addon)

        await notify(ObjectAddedEvent(container, self.context, container.__name__,
                                      payload=data))

        resp = {
            '@type': data['@type'],
            'id': data['id'],
            'title': data['title']
        }
        headers = {
            'Location': posixpath.join(self.request.path, data['id'])
        }

        return Response(content=resp, headers=headers)
Beispiel #19
0
async def test_sync_subscribers_only_called_once(dummy_guillotina):
    parent = create_content()
    ob = create_content(parent=parent)
    event = ObjectAddedEvent(ob, parent, ob.__name__, payload={})
    await notify(event)
    assert event.called == 1