Beispiel #1
0
    def test_unit__get_all_manageable(
        self, admin_user, session, app_config, user_api_factory, role_api_factory
    ):

        uapi = user_api_factory.get()
        # Checks a case without workspaces.
        wapi = WorkspaceApi(session=session, current_user=admin_user, config=app_config)
        assert [] == wapi.get_all_manageable()
        # Checks an admin_user gets all workspaces.
        w4 = wapi.create_workspace(label="w4")
        w3 = wapi.create_workspace(label="w3")
        w2 = wapi.create_workspace(label="w2")
        w1 = wapi.create_workspace(label="w1")
        assert [w1, w2, w3, w4] == wapi.get_all_manageable()
        # Checks a regular user gets none workspace.

        u = uapi.create_minimal_user("[email protected]", profile=Profile.USER, save_now=True)
        wapi = WorkspaceApi(session=session, current_user=u, config=app_config)
        rapi = role_api_factory.get()
        rapi.create_one(u, w4, UserRoleInWorkspace.READER, False)
        rapi.create_one(u, w3, UserRoleInWorkspace.CONTRIBUTOR, False)
        rapi.create_one(u, w2, UserRoleInWorkspace.CONTENT_MANAGER, False)
        rapi.create_one(u, w1, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
        assert [] == wapi.get_all_manageable()
        # Checks a manager gets only its own workspaces.
        u.profile = Profile.TRUSTED_USER
        rapi.delete_one(u.user_id, w2.workspace_id)
        rapi.create_one(u, w2, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
        assert [w1, w2] == wapi.get_all_manageable()
Beispiel #2
0
 def test_unit__get_known__user__distinct_workspaces_users_by_name__exclude_workspace(self):
     admin = self.session.query(models.User) \
         .filter(models.User.email == '*****@*****.**') \
         .one()
     api = UserApi(
         current_user=None,
         session=self.session,
         config=self.config,
     )
     u1 = api.create_user(
         email='email@email',
         name='name',
         do_notify=False,
         do_save=True,
     )
     u2 = api.create_user(
         email='email2@email2',
         name='name2',
         do_notify=False,
         do_save=True,
     )
     u3 = api.create_user(
         email='notfound@notfound',
         name='notfound',
         do_notify=False,
         do_save=True,
     )
     wapi = WorkspaceApi(
         current_user=admin,
         session=self.session,
         config=self.app_config,
     )
     workspace = wapi.create_workspace(
         'test workspace n°1',
         save_now=True)
     wapi = WorkspaceApi(
         current_user=admin,
         session=self.session,
         config=self.app_config,
     )
     workspace_2 = wapi.create_workspace(
         'test workspace n°2',
         save_now=True)
     role_api = RoleApi(
         current_user=admin,
         session=self.session,
         config=self.app_config,
     )
     role_api.create_one(u1, workspace, UserRoleInWorkspace.READER, False)
     role_api.create_one(u2, workspace_2, UserRoleInWorkspace.READER, False)
     role_api.create_one(u3, workspace, UserRoleInWorkspace.READER, False)
     role_api.create_one(u3, workspace_2, UserRoleInWorkspace.READER, False)
     api2 = UserApi(
         current_user=u3,
         session=self.session,
         config=self.config,
     )
     users = api2.get_known_user('name', exclude_workspace_ids=[workspace.workspace_id])
     assert len(users) == 1
     assert users[0] == u2
Beispiel #3
0
 def test_unit__get_known__user__distinct_workspaces_users_by_name__exclude_workspace_and_name(
     self
 ):
     admin = self.session.query(User).filter(User.email == "*****@*****.**").one()
     api = UserApi(current_user=None, session=self.session, config=self.app_config)
     u1 = api.create_user(email="email@email", name="name", do_notify=False, do_save=True)
     u2 = api.create_user(email="email2@email2", name="name2", do_notify=False, do_save=True)
     u3 = api.create_user(
         email="notfound@notfound", name="notfound", do_notify=False, do_save=True
     )
     u4 = api.create_user(email="email3@email3", name="name3", do_notify=False, do_save=True)
     wapi = WorkspaceApi(current_user=admin, session=self.session, config=self.app_config)
     workspace = wapi.create_workspace("test workspace n°1", save_now=True)
     wapi = WorkspaceApi(current_user=admin, session=self.session, config=self.app_config)
     workspace_2 = wapi.create_workspace("test workspace n°2", save_now=True)
     role_api = RoleApi(current_user=admin, session=self.session, config=self.app_config)
     role_api.create_one(u1, workspace, UserRoleInWorkspace.READER, False)
     role_api.create_one(u2, workspace_2, UserRoleInWorkspace.READER, False)
     role_api.create_one(u4, workspace_2, UserRoleInWorkspace.READER, False)
     role_api.create_one(u3, workspace, UserRoleInWorkspace.READER, False)
     role_api.create_one(u3, workspace_2, UserRoleInWorkspace.READER, False)
     api2 = UserApi(current_user=u3, session=self.session, config=self.app_config)
     users = api2.get_known_user(
         "name", exclude_workspace_ids=[workspace.workspace_id], exclude_user_ids=[u4.user_id]
     )
     assert len(users) == 1
     assert users[0] == u2
Beispiel #4
0
 def test_unit__get_all_manageable(self):
     admin = self.session.query(User) \
         .filter(User.email == '*****@*****.**').one()
     uapi = UserApi(
         session=self.session,
         current_user=admin,
         config=self.app_config,
     )
     # Checks a case without workspaces.
     wapi = WorkspaceApi(
         session=self.session,
         current_user=admin,
         config=self.app_config,
     )
     eq_([], wapi.get_all_manageable())
     # Checks an admin gets all workspaces.
     w4 = wapi.create_workspace(label='w4')
     w3 = wapi.create_workspace(label='w3')
     w2 = wapi.create_workspace(label='w2')
     w1 = wapi.create_workspace(label='w1')
     eq_([w1, w2, w3, w4], wapi.get_all_manageable())
     # Checks a regular user gets none workspace.
     gapi = GroupApi(
         session=self.session,
         current_user=None,
         config=self.app_config,
     )
     u = uapi.create_minimal_user('[email protected]', [gapi.get_one(Group.TIM_USER)],
                                  True)
     wapi = WorkspaceApi(
         session=self.session,
         current_user=u,
         config=self.app_config,
     )
     rapi = RoleApi(
         session=self.session,
         current_user=None,
         config=self.app_config,
     )
     rapi.create_one(u, w4, UserRoleInWorkspace.READER, False)
     rapi.create_one(u, w3, UserRoleInWorkspace.CONTRIBUTOR, False)
     rapi.create_one(u, w2, UserRoleInWorkspace.CONTENT_MANAGER, False)
     rapi.create_one(u, w1, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
     eq_([], wapi.get_all_manageable())
     # Checks a manager gets only its own workspaces.
     u.groups.append(gapi.get_one(Group.TIM_MANAGER))
     rapi.delete_one(u.user_id, w2.workspace_id)
     rapi.create_one(u, w2, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
     eq_([w1, w2], wapi.get_all_manageable())
Beispiel #5
0
 def contents_read_status(self,
                          context,
                          request: TracimRequest,
                          hapic_data=None):  # nopep8
     """
     get user_read status of contents
     """
     app_config = request.registry.settings['CFG']
     content_filter = hapic_data.query
     api = ContentApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     wapi = WorkspaceApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     workspace = None
     if hapic_data.path.workspace_id:
         workspace = wapi.get_one(hapic_data.path.workspace_id)
     last_actives = api.get_last_active(
         workspace=workspace,
         limit=None,
         before_content=None,
         content_ids=hapic_data.query.contents_ids or None)
     return [
         api.get_content_in_context(content) for content in last_actives
     ]
Beispiel #6
0
 def test_proxy_workspace_agenda__err__other_workspace_agenda(self) -> None:
     dbsession = get_tm_session(self.session_factory, transaction.manager)
     admin = dbsession.query(User).filter(
         User.email == "*****@*****.**").one()
     uapi = UserApi(current_user=admin,
                    session=dbsession,
                    config=self.app_config)
     gapi = GroupApi(current_user=admin,
                     session=dbsession,
                     config=self.app_config)
     groups = [gapi.get_one_with_name("users")]
     uapi.create_user(
         "*****@*****.**",
         password="******",
         do_save=True,
         do_notify=False,
         groups=groups,
     )
     workspace_api = WorkspaceApi(current_user=admin,
                                  session=dbsession,
                                  config=self.app_config,
                                  show_deleted=True)
     workspace = workspace_api.create_workspace("test", save_now=True)
     transaction.commit()
     self.testapp.authorization = ("Basic", ("*****@*****.**",
                                             "*****@*****.**"))
     result = self.testapp.get("/agenda/workspace/{}/".format(
         workspace.workspace_id),
                               status=403)
     assert result.json_body["code"] == 5001
Beispiel #7
0
    def should_anonymize(self,
                         user: User,
                         owned_workspace_will_be_deleted: bool = False
                         ) -> UserNeedAnonymization:
        wapi = WorkspaceApi(config=self.app_config,
                            session=self.session,
                            current_user=user,
                            show_deleted=True)
        user_owned_workspaces_to_filter = wapi.get_all_for_user(
            user, include_owned=True, include_with_role=False)

        query = self.session.query(ContentRevisionRO)
        if owned_workspace_will_be_deleted:
            query = query.filter(~ContentRevisionRO.workspace_id.in_([
                workspace.workspace_id
                for workspace in user_owned_workspaces_to_filter
            ]))
            user_blocking_workspaces = []
        else:
            user_blocking_workspaces = user_owned_workspaces_to_filter

        query = query.filter(ContentRevisionRO.owner_id == user.user_id)
        user_blocking_revisions = query.all()
        return UserNeedAnonymization(
            blocking_workspaces=user_blocking_workspaces,
            blocking_revisions=user_blocking_revisions)
Beispiel #8
0
 def create_workspace(self,
                      context,
                      request: TracimRequest,
                      hapic_data=None):
     """
     Create a workspace. This route is for trusted users and administrators.
     """
     app_config = request.registry.settings["CFG"]  # type: CFG
     wapi = WorkspaceApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config  # User
     )
     parent = None
     if hapic_data.body.parent_id:
         parent = wapi.get_one(workspace_id=hapic_data.body.parent_id)
     workspace = wapi.create_workspace(
         label=hapic_data.body.label,
         description=hapic_data.body.description,
         access_type=hapic_data.body.access_type,
         save_now=True,
         agenda_enabled=hapic_data.body.agenda_enabled,
         public_download_enabled=hapic_data.body.public_download_enabled,
         public_upload_enabled=hapic_data.body.public_upload_enabled,
         default_user_role=hapic_data.body.default_user_role,
         parent=parent,
     )
     wapi.execute_created_workspace_actions(workspace)
     return wapi.get_workspace_with_context(workspace)
Beispiel #9
0
 def test_get_notifiable_roles(self):
     admin = self.session.query(User) \
         .filter(User.email == '*****@*****.**').one()
     wapi = WorkspaceApi(
         session=self.session,
         config=self.app_config,
         current_user=admin,
     )
     w = wapi.create_workspace(label='workspace w', save_now=True)
     uapi = UserApi(session=self.session,
                    current_user=admin,
                    config=self.app_config)
     u = uapi.create_minimal_user(email='[email protected]', save_now=True)
     eq_([], wapi.get_notifiable_roles(workspace=w))
     rapi = RoleApi(
         session=self.session,
         current_user=admin,
         config=self.app_config,
     )
     r = rapi.create_one(u, w, UserRoleInWorkspace.READER, with_notif=True)
     eq_([
         r,
     ], wapi.get_notifiable_roles(workspace=w))
     u.is_active = False
     eq_([], wapi.get_notifiable_roles(workspace=w))
Beispiel #10
0
    def used_space(self) -> int:
        from tracim_backend.lib.core.workspace import WorkspaceApi

        wapi = WorkspaceApi(current_user=None,
                            session=self.dbsession,
                            config=self.config)
        return wapi.get_user_used_space(self.user)
Beispiel #11
0
 def test__unit__get_notifiable_roles__ok__nominal_case(self):
     admin = self.session.query(User).filter(
         User.email == "*****@*****.**").one()
     wapi = WorkspaceApi(session=self.session,
                         config=self.app_config,
                         current_user=admin)
     workspace = wapi.create_workspace(label="workspace w", save_now=True)
     uapi = UserApi(session=self.session,
                    current_user=admin,
                    config=self.app_config)
     user_1 = uapi.create_user(email="[email protected]",
                               auth_type=AuthType.INTERNAL,
                               do_save=True,
                               do_notify=False)
     user_2 = uapi.create_user(email="[email protected]",
                               auth_type=AuthType.INTERNAL,
                               do_save=True,
                               do_notify=False)
     assert wapi.get_notifiable_roles(workspace=workspace) == []
     rapi = RoleApi(session=self.session,
                    current_user=admin,
                    config=self.app_config)
     role_1 = rapi.create_one(user_1,
                              workspace,
                              UserRoleInWorkspace.READER,
                              with_notif=True)
     role_2 = rapi.create_one(user_2,
                              workspace,
                              UserRoleInWorkspace.READER,
                              with_notif=False)
     assert role_1 in wapi.get_notifiable_roles(workspace=workspace)
     assert role_2 not in wapi.get_notifiable_roles(workspace=workspace)
Beispiel #12
0
    def test_unit__create_workspace_same__ok__same_workspace_name_allowed(
        self, admin_user, session, app_config
    ):

        wapi = WorkspaceApi(session=session, current_user=admin_user, config=app_config)
        wapi.create_workspace(label="business", save_now=True)
        wapi.create_workspace(label="business", save_now=True)
Beispiel #13
0
    def test_api___simple_search_ok__no_search_string(self) -> None:
        dbsession = get_tm_session(self.session_factory, transaction.manager)
        admin = dbsession.query(User).filter(User.email == "*****@*****.**").one()
        uapi = UserApi(current_user=admin, session=dbsession, config=self.app_config)
        gapi = GroupApi(current_user=admin, session=dbsession, config=self.app_config)
        groups = [gapi.get_one_with_name("trusted-users")]
        user = uapi.create_user(
            "*****@*****.**",
            password="******",
            do_save=True,
            do_notify=False,
            groups=groups,
        )
        workspace_api = WorkspaceApi(
            current_user=admin, session=dbsession, config=self.app_config, show_deleted=True
        )
        workspace = workspace_api.create_workspace("test", save_now=True)
        rapi = RoleApi(current_user=admin, session=dbsession, config=self.app_config)
        rapi.create_one(user, workspace, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
        api = ContentApi(session=dbsession, current_user=user, config=self.app_config)
        api.create(
            content_type_slug="html-document", workspace=workspace, label="test", do_save=True
        )
        transaction.commit()

        self.testapp.authorization = ("Basic", ("*****@*****.**", "*****@*****.**"))
        res = self.testapp.get("/api/v2/search/content".format(), status=200)
        search_result = res.json_body
        assert search_result
        assert search_result["total_hits"] == 0
        assert search_result["is_total_hits_accurate"] is True
        assert len(search_result["contents"]) == 0
Beispiel #14
0
    def _get_content(self, content_path_fetcher):
        path = content_path_fetcher()
        content_path = self.reduce_path(path)
        splited_local_path = content_path.strip('/').split('/')
        workspace_name = webdav_convert_file_name_to_bdd(splited_local_path[0])
        wapi = WorkspaceApi(
            current_user=self.current_user,
            session=self.dbsession,
            config=self.app_config,
        )
        workspace = wapi.get_one_by_label(workspace_name)
        parents = []
        if len(splited_local_path) > 2:
            parent_string = splited_local_path[1:-1]
            parents = [
                webdav_convert_file_name_to_bdd(x) for x in parent_string
            ]

        content_api = ContentApi(config=self.app_config,
                                 current_user=self.current_user,
                                 session=self.dbsession)
        return content_api.get_one_by_filename_and_parent_labels(
            content_label=webdav_convert_file_name_to_bdd(basename(path)),
            content_parent_labels=parents,
            workspace=workspace,
        )
Beispiel #15
0
 def account_contents_read_status(self,
                                  context,
                                  request: TracimRequest,
                                  hapic_data=None):
     """
     get user_read status of contents
     """
     app_config = request.registry.settings["CFG"]  # type: CFG
     api = ContentApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config  # User
     )
     wapi = WorkspaceApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config  # User
     )
     workspace = None
     if hapic_data.path.workspace_id:
         workspace = wapi.get_one(hapic_data.path.workspace_id)
     last_actives = api.get_last_active(
         workspace=workspace,
         limit=None,
         before_content=None,
         content_ids=hapic_data.query.content_ids or None,
     )
     return [
         api.get_content_in_context(content) for content in last_actives
     ]
Beispiel #16
0
 def enable_workspace_notification(self,
                                   context,
                                   request: TracimRequest,
                                   hapic_data=None):  # nopep8
     """
     enable workspace notification
     """
     app_config = request.registry.settings['CFG']
     api = ContentApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     wapi = WorkspaceApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     workspace = wapi.get_one(hapic_data.path.workspace_id)
     wapi.enable_notifications(request.candidate_user, workspace)
     rapi = RoleApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     role = rapi.get_one(request.candidate_user.user_id,
                         workspace.workspace_id)
     wapi.save(workspace)
     return
Beispiel #17
0
    def _create_content_event(self, operation: OperationType, content: Content,
                              context: TracimContext) -> None:
        current_user = context.safe_current_user()
        content_api = ContentApi(context.dbsession, current_user, self._config)
        content_in_context = content_api.get_content_in_context(content)
        content_schema = EventApi.get_content_schema_for_type(content.type)
        content_dict = content_schema.dump(content_in_context).data

        workspace_api = WorkspaceApi(context.dbsession,
                                     current_user,
                                     self._config,
                                     show_deleted=True)
        workspace_in_context = workspace_api.get_workspace_with_context(
            workspace_api.get_one(content_in_context.workspace.workspace_id))
        fields = {
            Event.CONTENT_FIELD:
            content_dict,
            Event.WORKSPACE_FIELD:
            EventApi.workspace_schema.dump(workspace_in_context).data,
        }
        event_api = EventApi(current_user, context.dbsession, self._config)
        event_api.create_event(
            entity_type=EntityType.CONTENT,
            operation=operation,
            additional_fields=fields,
            entity_subtype=content.type,
            context=context,
        )
Beispiel #18
0
 def last_active_content(self,
                         context,
                         request: TracimRequest,
                         hapic_data=None):
     """
     Get last_active_content for user
     """
     app_config = request.registry.settings["CFG"]  # type: CFG
     content_filter = hapic_data.query
     api = ContentApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     wapi = WorkspaceApi(
         current_user=request.candidate_user,  # User
         session=request.dbsession,
         config=app_config,
     )
     workspace = None
     if hapic_data.path.workspace_id:
         workspace = wapi.get_one(hapic_data.path.workspace_id)
     before_content = None
     if content_filter.before_content_id:
         before_content = api.get_one(
             content_id=content_filter.before_content_id,
             workspace=workspace,
             content_type=content_type_list.Any_SLUG,
         )
     last_actives = api.get_last_active(workspace=workspace,
                                        limit=content_filter.limit or None,
                                        before_content=before_content)
     return [
         api.get_content_in_context(content) for content in last_actives
     ]
Beispiel #19
0
 def _get_current_workspace(
         self,
         user: User,
         request: 'TracimRequest'
 ) -> Workspace:
     """
     Get current workspace from request
     :param user: User who want to check the workspace
     :param request: pyramid request
     :return: current workspace
     """
     workspace_id = ''
     try:
         if 'workspace_id' in request.matchdict:
             workspace_id_str = request.matchdict['workspace_id']
             if not isinstance(workspace_id_str, str) or not workspace_id_str.isdecimal():  # nopep8
                 raise InvalidWorkspaceId('workspace_id is not a correct integer')  # nopep8
             workspace_id = int(request.matchdict['workspace_id'])
         if not workspace_id:
             raise WorkspaceNotFoundInTracimRequest('No workspace_id property found in request')  # nopep8
         wapi = WorkspaceApi(
             current_user=user,
             session=request.dbsession,
             config=request.registry.settings['CFG'],
             show_deleted=True,
         )
         workspace = wapi.get_one(workspace_id)
     except NoResultFound as exc:
         raise WorkspaceNotFound(
             'Workspace {} does not exist '
             'or is not visible for this user'.format(workspace_id)
         ) from exc
     return workspace
Beispiel #20
0
    def test__unit__get_notifiable_roles__ok__do_not_show_deleted(
        self, admin_user, session, app_config, user_api_factory, role_api_factory
    ):

        wapi = WorkspaceApi(session=session, config=app_config, current_user=admin_user)
        workspace = wapi.create_workspace(label="workspace w", save_now=True)
        uapi = user_api_factory.get()
        user_1 = uapi.create_user(
            email="[email protected]", auth_type=AuthType.INTERNAL, do_save=True, do_notify=False
        )
        user_2 = uapi.create_user(
            email="[email protected]", auth_type=AuthType.INTERNAL, do_save=True, do_notify=False
        )
        assert wapi.get_notifiable_roles(workspace=workspace) == []

        rapi = role_api_factory.get()
        role_1 = rapi.create_one(user_1, workspace, UserRoleInWorkspace.READER, with_notif=True)
        role_2 = rapi.create_one(user_2, workspace, UserRoleInWorkspace.READER, with_notif=True)

        assert role_1 in wapi.get_notifiable_roles(workspace=workspace)
        assert role_2 in wapi.get_notifiable_roles(workspace=workspace)

        user_1.is_deleted = True
        assert role_1 not in wapi.get_notifiable_roles(workspace=workspace)
        assert role_2 in wapi.get_notifiable_roles(workspace=workspace)
Beispiel #21
0
    def test_children(self, admin_user, session, app_config,
                      content_api_factory, content_type_list):
        workspace = WorkspaceApi(current_user=admin_user,
                                 session=session,
                                 config=app_config).create_workspace(
                                     "workspace_1", save_now=True)
        folder = Content(type=content_type_list.Folder.slug, owner=admin_user)
        folder.label = "folder_1"
        folder.workspace = workspace
        session.add(folder)
        session.flush()

        thread = Content(type=content_type_list.Thread.slug,
                         owner=admin_user,
                         parent=folder)
        thread.label = "thread_1"
        thread.workspace = workspace
        session.add(folder)
        session.flush()
        workspace = session.query(Workspace).filter(
            Workspace.label == "workspace_1").one()
        content_api = content_api_factory.get()
        folder = content_api.get_canonical_query().filter(
            Content.label == "folder_1").one()
        assert [folder] == list(workspace.get_valid_children())
Beispiel #22
0
 def _create_subscription_event(self, operation: OperationType,
                                subscription: WorkspaceSubscription,
                                context: TracimContext) -> None:
     current_user = context.safe_current_user()
     workspace_api = WorkspaceApi(
         session=context.dbsession,
         config=self._config,
         current_user=None,
     )
     workspace_in_context = workspace_api.get_workspace_with_context(
         workspace_api.get_one(subscription.workspace_id))
     user_api = UserApi(current_user,
                        context.dbsession,
                        self._config,
                        show_deleted=True)
     subscription_author_in_context = user_api.get_user_with_context(
         subscription.author)
     fields = {
         Event.WORKSPACE_FIELD:
         EventApi.workspace_schema.dump(workspace_in_context).data,
         Event.SUBSCRIPTION_FIELD:
         EventApi.workspace_subscription_schema.dump(subscription).data,
         Event.USER_FIELD:
         EventApi.user_schema.dump(subscription_author_in_context).data,
     }
     event_api = EventApi(current_user, context.dbsession, self._config)
     event_api.create_event(
         entity_type=EntityType.WORKSPACE_SUBSCRIPTION,
         operation=operation,
         additional_fields=fields,
         context=context,
     )
Beispiel #23
0
 def update_workspace(self,
                      context,
                      request: TracimRequest,
                      hapic_data=None):
     """
     Update a workspace. This route is for trusted users and administrators.
     Note : a trusted user can only update spaces on which he/she is space manager
     """
     app_config = request.registry.settings["CFG"]  # type: CFG
     wapi = WorkspaceApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config  # User
     )
     wapi.update_workspace(
         request.current_workspace,
         label=hapic_data.body.label,
         description=hapic_data.body.description,
         agenda_enabled=hapic_data.body.agenda_enabled,
         public_download_enabled=hapic_data.body.public_download_enabled,
         public_upload_enabled=hapic_data.body.public_upload_enabled,
         default_user_role=hapic_data.body.default_user_role,
         save_now=True,
     )
     wapi.execute_update_workspace_actions(request.current_workspace)
     return wapi.get_workspace_with_context(request.current_workspace)
Beispiel #24
0
 def delete_comment(self, context, request: TracimRequest, hapic_data=None):
     """
     Delete comment
     """
     app_config = request.registry.settings['CFG']
     api = ContentApi(
         show_archived=True,
         show_deleted=True,
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config,
     )
     wapi = WorkspaceApi(
         current_user=request.current_user,
         session=request.dbsession,
         config=app_config,
     )
     workspace = wapi.get_one(hapic_data.path.workspace_id)
     parent = api.get_one(hapic_data.path.content_id,
                          content_type=content_type_list.Any_SLUG,
                          workspace=workspace)
     comment = api.get_one(
         hapic_data.path.comment_id,
         content_type=content_type_list.Comment.slug,
         workspace=workspace,
         parent=parent,
     )
     with new_revision(session=request.dbsession,
                       tm=transaction.manager,
                       content=comment):
         api.delete(comment)
     return
Beispiel #25
0
    def moveRecursive(self, destpath):
        # INFO - G.M - 2018-12-11 - We only allow renaming
        if dirname(normpath(
                destpath)) == self.environ["http_authenticator.realm"]:
            # FIXME - G.M - 2018-12-11 - For an unknown reason current_workspace
            # of tracim_context is here invalid.
            self.tracim_context._current_workspace = self.workspace
            try:
                can_modify_workspace.check(self.tracim_context)
            except TracimException as exc:
                raise DAVError(HTTP_FORBIDDEN, contextinfo=str(exc))

            try:
                workspace_api = WorkspaceApi(current_user=self.user,
                                             session=self.session,
                                             config=self.provider.app_config)
                workspace_api.update_workspace(
                    workspace=self.workspace,
                    label=webdav_convert_file_name_to_bdd(
                        basename(normpath(destpath))),
                    description=self.workspace.description,
                )
                self.session.add(self.workspace)
                self.session.flush()
                workspace_api.execute_update_workspace_actions(self.workspace)
                transaction.commit()
            except TracimException as exc:
                raise DAVError(HTTP_FORBIDDEN, contextinfo=str(exc))
Beispiel #26
0
    def test_func__create_new_content_with_notification__ok__nominal_case(self):
        uapi = UserApi(current_user=None, session=self.session, config=self.app_config)
        current_user = uapi.get_one_by_email("*****@*****.**")
        # Create new user with notification enabled on w1 workspace
        wapi = WorkspaceApi(current_user=current_user, session=self.session, config=self.app_config)
        workspace = wapi.get_one_by_label("Recipes")
        user = uapi.get_one_by_email("*****@*****.**")
        wapi.enable_notifications(user, workspace)

        api = ContentApi(current_user=user, session=self.session, config=self.app_config)
        item = api.create(
            content_type_list.Folder.slug, workspace, None, "parent", do_save=True, do_notify=False
        )
        api.create(
            content_type_list.File.slug, workspace, item, "file1", do_save=True, do_notify=True
        )
        # Send mail async from redis queue with daemon
        daemon = MailSenderDaemon(self.app_config, burst=True)
        daemon.run()
        # check mail received
        response = self.get_mailhog_mails()
        headers = response[0]["Content"]["Headers"]
        assert headers["From"][0] == '"Bob i. via Tracim" <test_user_from+3@localhost>'
        assert headers["To"][0] == "Global manager <*****@*****.**>"
        assert headers["Subject"][0] == "[TRACIM] [Recipes] file1 (Open)"
        assert headers["References"][0] == "test_user_refs+22@localhost"
        assert (
            headers["Reply-to"][0]
            == '"Bob i. & all members of Recipes" <test_user_reply+22@localhost>'
        )
Beispiel #27
0
 def __init__(
     self,
     path: str,
     environ: dict,
     label: str,
     workspace: typing.Optional[Workspace],
     provider: "TracimDavProvider",
     tracim_context: "WebdavTracimContext",
     list_orphan_workspaces: bool = False,
 ) -> None:
     """
     Some rules:
     - if workspace given is None, return workspaces with no parent
     - if workspace given is correct, return children workspaces of this workspace
     - if list_orphan_workspaces is True, it
      adds user-known workspaces without any user-known parent to the list.
      - in case of workspace collision, only the first named workspace (sorted by workspace_id
      from lower to higher) will be returned
     """
     self.path = path
     self.environ = environ
     self.workspace = workspace
     self.tracim_context = tracim_context
     self.user = tracim_context.current_user
     self.session = tracim_context.dbsession
     self.label = label
     self.provider = provider
     self.workspace_api = WorkspaceApi(
         current_user=self.user,
         session=self.session,
         force_role=True,
         config=tracim_context.app_config,
     )
     self.list_orphan_workspaces = list_orphan_workspaces
Beispiel #28
0
    def guest_download_check(self,
                             context,
                             request: TracimRequest,
                             hapic_data=None) -> None:
        """
        Check if share token is correct and password given valid
        """
        app_config = request.registry.settings["CFG"]  # type: CFG
        api = ShareLib(current_user=None,
                       session=request.dbsession,
                       config=app_config)
        content_share = api.get_content_share_by_token(
            share_token=hapic_data.path.share_token)  # type: ContentShare

        # TODO - G.M - 2019-08-01 - verify in access to content share can be granted
        # we should considered do these check at decorator level
        api.check_password(content_share, password=hapic_data.body.password)
        content = ContentApi(current_user=None,
                             session=request.dbsession,
                             config=app_config).get_one(
                                 content_share.content_id,
                                 content_type=content_type_list.Any_SLUG)
        workspace_api = WorkspaceApi(current_user=None,
                                     session=request.dbsession,
                                     config=app_config)
        workspace = workspace_api.get_one(content.workspace_id)
        workspace_api.check_public_download_enabled(workspace)
        if content.type not in shareables_content_type:
            raise ContentTypeNotAllowed()
Beispiel #29
0
    def add_permission_to_workspace(
        self,
        workspace: Workspace,
        emails: typing.List[str],
        password: typing.Optional[str] = None,
        do_notify=False,
    ) -> typing.List[UploadPermission]:
        upload_permissions = []
        created = datetime.utcnow()
        upload_permission_group_uuid = str(uuid.uuid4().hex)
        for email in emails:
            upload_permission = UploadPermission(
                author=self._user,
                workspace_id=workspace.workspace_id,
                email=email.lower(),
                token=str(uuid.uuid4()),
                password=password,
                type=UploadPermissionType.EMAIL,
                created=created,
                upload_permission_group_uuid=upload_permission_group_uuid,
                enabled=True,
            )
            self.save(upload_permission)
            upload_permissions.append(upload_permission)
            self._session.flush()

        if do_notify:
            userlib = UserApi(config=self._config,
                              current_user=self._user,
                              session=self._session)
            workspace_lib = WorkspaceApi(config=self._config,
                                         current_user=self._user,
                                         session=self._session)
            try:
                email_manager = self._get_email_manager(
                    self._config, self._session)
                email_manager.notify_upload_permission(
                    emitter=userlib.get_user_with_context(self._user),
                    workspace_in_context=workspace_lib.
                    get_workspace_with_context(workspace),
                    upload_permission_receivers=self.
                    get_upload_permissions_in_context(upload_permissions),
                    upload_permission_password=password,
                )
            # FIXME - G.M - 2018-11-02 - hack: accept bad recipient user creation
            # this should be fixed to find a solution to allow "fake" email but
            # also have clear error case for valid mail.
            except SMTPRecipientsRefused:
                logger.warning(
                    self,
                    "Upload Permission initied by user {} but SMTP "
                    "server refuse to send notification".format(
                        self._user.login),
                )
            except SMTPException as exc:
                raise NotificationSendingFailed(
                    "Notification for Upload Permission can't be send "
                    "(SMTP error).") from exc
        return upload_permissions
Beispiel #30
0
    def test_api___simple_search_ok__by_comment_content(
        self,
        created_content_name,
        search_string,
        nb_content_result,
        first_search_result_content_name,
        first_created_comment_content,
        second_created_comment_content,
    ) -> None:
        dbsession = get_tm_session(self.session_factory, transaction.manager)
        admin = dbsession.query(User).filter(User.email == "*****@*****.**").one()
        uapi = UserApi(current_user=admin, session=dbsession, config=self.app_config)
        gapi = GroupApi(current_user=admin, session=dbsession, config=self.app_config)
        groups = [gapi.get_one_with_name("trusted-users")]
        user = uapi.create_user(
            "*****@*****.**",
            password="******",
            do_save=True,
            do_notify=False,
            groups=groups,
        )
        workspace_api = WorkspaceApi(
            current_user=admin, session=dbsession, config=self.app_config, show_deleted=True
        )
        workspace = workspace_api.create_workspace("test", save_now=True)
        rapi = RoleApi(current_user=admin, session=dbsession, config=self.app_config)
        rapi.create_one(user, workspace, UserRoleInWorkspace.WORKSPACE_MANAGER, False)
        api = ContentApi(session=dbsession, current_user=user, config=self.app_config)
        content = api.create(
            content_type_slug="html-document",
            workspace=workspace,
            label=created_content_name,
            do_save=True,
        )
        api.create_comment(
            workspace=workspace, parent=content, content=first_created_comment_content, do_save=True
        )
        api.create_comment(
            workspace=workspace,
            parent=content,
            content=second_created_comment_content,
            do_save=True,
        )
        api.create(
            content_type_slug="html-document", workspace=workspace, label="report", do_save=True
        )
        api.create(
            content_type_slug="thread", workspace=workspace, label="discussion", do_save=True
        )
        transaction.commit()

        self.testapp.authorization = ("Basic", ("*****@*****.**", "*****@*****.**"))
        params = {"search_string": search_string}
        res = self.testapp.get("/api/v2/search/content".format(), status=200, params=params)
        search_result = res.json_body
        assert search_result
        assert search_result["total_hits"] == nb_content_result
        assert search_result["is_total_hits_accurate"] is False
        assert search_result["contents"][0]["label"] == first_search_result_content_name