Ejemplo n.º 1
0
 def isRealmUser(
     self, realmname: str, username: str, environ: typing.Dict[str, typing.Any]
 ) -> bool:
     """
     Called to check if for a given root, the username exists (though here we don't make difference between
     root as we're always starting at tracim's root
     """
     session = environ["tracim_context"].dbsession  # type: Session
     api = UserApi(None, session, self.app_config)
     try:
         api.get_one_by_login(login=username)
         return True
     # TODO - G.M - 2019-04-25 - do better exception handling here,
     # see https://github.com/tracim/tracim/issues/1636
     except Exception:
         return False
Ejemplo n.º 2
0
 def _get_user(self, get_webdav_username: typing.Callable) -> User:
     login = get_webdav_username()
     uapi = UserApi(None,
                    show_deleted=True,
                    session=self.dbsession,
                    config=self.app_config)
     return uapi.get_one_by_login(login)
Ejemplo n.º 3
0
class UpdateUserCommand(UserCommand):
    def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
        parser = super().get_parser(prog_name)
        parser.add_argument(
            "-l",
            "--login",
            help="the user's login (either the email address or the username)",
            dest="login",
            required=True,
        )
        return parser

    def get_description(self) -> str:
        return """Edit the account of a user"""

    def take_app_action(self, parsed_args: argparse.Namespace,
                        app_context: AppEnvironment) -> None:
        # TODO - G.M - 05-04-2018 -Refactor this in order
        # to not setup object var outside of __init__ .
        self._session = app_context["request"].dbsession
        self._app_config = app_context["registry"].settings["CFG"]
        self._user_api = UserApi(current_user=None,
                                 session=self._session,
                                 config=self._app_config)
        user = self._user_api.get_one_by_login(parsed_args.login)
        profile = None
        if parsed_args.profile:
            profile = Profile.get_profile_from_slug(parsed_args.profile)
        try:
            user = self._user_api.update(
                user=user,
                email=parsed_args.email,
                name=parsed_args.public_name,
                password=parsed_args.password,
                timezone=parsed_args.timezone,
                username=parsed_args.username,
                allowed_space=parsed_args.allowed_space,
                profile=profile,
                do_save=True,
            )
            self._user_api.execute_created_user_actions(user)
        except TracimException as exc:
            self._session.rollback()
            print("Error: " + str(exc))
            print("User not updated.")
            raise exc
        print("User updated")
Ejemplo n.º 4
0
    def take_app_action(self, parsed_args: argparse.Namespace,
                        app_context: AppEnvironment) -> None:
        self._session = app_context["request"].dbsession
        self._app_config = app_context["registry"].settings["CFG"]

        if parsed_args.dry_run_mode:
            print("(!) Running in dry-run mode, not change will be applied.")
            app_context["request"].tm.doom()

        with unprotected_content_revision(self._session) as session:
            uapi = UserApi(
                config=self._app_config,
                session=session,
                current_user=None,
                show_deleted=True,
                show_deactivated=True,
            )
            user_list = []  # type: typing.List[User]
            for login in parsed_args.logins:
                try:
                    user = uapi.get_one_by_login(login)
                    user_list.append(user)
                except UserDoesNotExist as exc:
                    print('ERROR: user with email "{}" does not exist'.format(
                        login))
                    raise exc
            for user in user_list:
                print("~~~~~~~~~~")
                cleanup_lib = CleanupLib(session,
                                         self._app_config,
                                         dry_run_mode=parsed_args.dry_run_mode)
                print("anonymize user {}.".format(user.user_id))
                cleanup_lib.anonymize_user(
                    user,
                    anonymized_user_display_name=parsed_args.anonymize_name)
                self._session.flush()
                print('user {} anonymized to "{} <{}/{}>".'.format(
                    user.user_id, user.display_name, user.email,
                    user.username))
                print("~~~~~~~~~~")
Ejemplo n.º 5
0
    def take_app_action(self, parsed_args: argparse.Namespace,
                        app_context: AppEnvironment) -> None:
        self._session = app_context["request"].dbsession
        self._app_config = app_context["registry"].settings["CFG"]

        delete_user_revision = parsed_args.force or parsed_args.delete_revisions
        delete_owned_sharespaces = (parsed_args.force
                                    or parsed_args.best_effort
                                    or parsed_args.delete_sharespaces)
        anonymize_if_required = parsed_args.best_effort or parsed_args.anonymize_if_required

        if parsed_args.dry_run_mode:
            print("(!) Running in dry-run mode, no changes will be applied.")
            app_context["request"].tm.doom()
        if parsed_args.force:
            print("(!) Running in force mode")
        if parsed_args.best_effort:
            print("(!) Running in best-effort mode")

        if delete_user_revision:
            print(
                "/!\\ Delete all user revisions, database created may be broken /!\\."
            )
        if delete_owned_sharespaces:
            print("(!) User owned sharespaces will be deleted too.")
        if anonymize_if_required:
            print("(!) Will anonymize user if not possible to delete it")
            if parsed_args.anonymize_name:
                print('(!) Custom anonymize name choosen is: "{}"'.format(
                    parsed_args.anonymize_name))
        print("")
        deleted_user_ids = set()  # typing.Set[int]
        deleted_workspace_ids = set()  # typing.Set[int]
        with unprotected_content_revision(self._session) as session:
            uapi = UserApi(
                config=self._app_config,
                session=session,
                current_user=None,
                show_deleted=True,
                show_deactivated=True,
            )
            user_list = []  # type: typing.List[User]
            for login in parsed_args.logins:
                try:
                    user = uapi.get_one_by_login(login)
                    user_list.append(user)
                except UserDoesNotExist as exc:
                    print(
                        'ERROR: user with email/username "{}" does not exist'.
                        format(login))
                    raise exc
            print("~~~~")
            print("Deletion of user from Database")
            print("~~~~\n")
            print("~~~~")
            for user in user_list:
                cleanup_lib = CleanupLib(session,
                                         self._app_config,
                                         dry_run_mode=parsed_args.dry_run_mode)
                deleted_user_ids_result = self._delete_user_database_info(
                    user,
                    force_delete_all_user_revisions=delete_user_revision,
                    anonymize_if_required=anonymize_if_required,
                    delete_owned_workspaces=delete_owned_sharespaces,
                    anonymized_user_display_name=parsed_args.anonymize_name,
                    cleanup_lib=cleanup_lib,
                )
                deleted_user_ids.add(deleted_user_ids_result.user_id)
                deleted_workspace_ids.update(
                    deleted_user_ids_result.workspace_ids)
                print("~~~~")
            print(
                "deletion of user(s) from database process almost finished, change will be applied at end "
                "of this script.\n")
            print("~~~~")
            print("Deletion of Caldav Agenda\n")
            app_lib = ApplicationApi(app_list=app_list)
            if app_lib.exist(AGENDA__APP_SLUG):
                # INFO - G.M - 2019-12-13 - cleanup agenda at end of process
                if deleted_workspace_ids:
                    deleted_workspace_ids_str = [
                        '"{}"'.format(workspace_id)
                        for workspace_id in deleted_workspace_ids
                    ]
                    print("delete agenda of workspaces {}".format(
                        ", ".join(deleted_workspace_ids_str)))
                    for workspace_id in deleted_workspace_ids:
                        try:
                            cleanup_lib.delete_workspace_agenda(workspace_id)
                        except AgendaNotFoundError:
                            print(
                                'Warning: Cannot delete agenda for workspace "{}", agenda not found. Agenda path may be incorrect or agenda not created'
                                .format(workspace_id))
                            print(traceback.format_exc())

                if deleted_user_ids:
                    deleted_user_ids_str = [
                        '"{}"'.format(user_id) for user_id in deleted_user_ids
                    ]
                    print("delete agenda of users {}".format(
                        ", ".join(deleted_user_ids_str)))
                    for user_id in deleted_user_ids:
                        try:
                            cleanup_lib.delete_user_agenda(user_id)
                        except AgendaNotFoundError:
                            print(
                                'Warning: Cannot delete agenda for user "{}", agenda not found. Agenda path may be incorrect or agenda not created'
                                .format(user_id))
                            print(traceback.format_exc())
            else:
                print(
                    "Warning ! Agenda app not enabled, agenda will not be deleted."
                )
            print("~~~~")
            print("deletion of Agenda process finished")
            print("~~~~")
            if parsed_args.dry_run_mode:
                print("Finished (dry-run mode, no change applied)")
            else:
                print("Finished")