From fc1681928b028c2f0910af84d22488b333d23d49 Mon Sep 17 00:00:00 2001 From: Frank Lanitz Date: Sun, 23 Jan 2022 21:24:38 +0100 Subject: [PATCH] Add a CLI to delete a user with it's profile information --- ki/actions/__init__.py | 1 + ki/actions/delete_profile.py | 52 ++++++++++++++++++++++++++++++++++++ ki/commands.py | 10 +++++++ 3 files changed, 63 insertions(+) create mode 100644 ki/actions/delete_profile.py diff --git a/ki/actions/__init__.py b/ki/actions/__init__.py index 7bf583d..e0755cd 100644 --- a/ki/actions/__init__.py +++ b/ki/actions/__init__.py @@ -3,3 +3,4 @@ # SPDX-License-Identifier: AGPL-3.0-or-later from ki.actions.seed import seed # noqa +from ki.actions.delete_profile import delete_profile # noqa diff --git a/ki/actions/delete_profile.py b/ki/actions/delete_profile.py new file mode 100644 index 0000000..2898fdb --- /dev/null +++ b/ki/actions/delete_profile.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: WTF Kooperative eG +# +# SPDX-License-Identifier: AGPL-3.0-or-later + +from sqlalchemy.exc import NoResultFound +from app import app, db +from ki.models import User +import sys + + +def delete_profile(nickname: str): + + # Getting the user + try: + user = User.query.filter(User.auth_id.__eq__(nickname)).one() + except NoResultFound: + sys.exit(f'Username »{nickname}« not found') + + app.logger.info(f'Starting to delete user »{nickname}.') + + # Deleting associated languages skills + try: + for language in (user.profile.languages): + print(language.language_id) + app.logger.info(f'Deleting language skil »{language.language_id}« for »{nickname}«.') + db.session.delete(language) + db.session.commit() + except AttributeError: + # No languages left over + pass + + # Deleting associated skills + try: + app.logger.info(f'Deleting skils for »{nickname}«.') + for skill in user.profile.skills: + db.session.delete(skill) + db.session.commit() + except AttributeError: + # No skills left over + pass + + # Cleaning up profile + try: + app.logger.info(f'Deleting profile for »{nickname}«.') + db.session.delete(user.profile) + except: + # No profile to be deleted + pass + # Deleting the user + app.logger.info(f'Delete user »{nickname}«.') + db.session.delete(user) + db.session.commit() diff --git a/ki/commands.py b/ki/commands.py index fa5ce2f..9c7cf99 100644 --- a/ki/commands.py +++ b/ki/commands.py @@ -6,9 +6,19 @@ import click from app import app from ki.actions import seed +from ki.actions import delete_profile @app.cli.command("seed") @click.option("--dev", is_flag=True) def seed_command(dev): seed(dev) + + +@app.cli.command("delete", help="Delete a user profile") +@click.option( + "--profile", + help="Username of profile", +) +def delete_command(profile): + delete_profile(profile)