From 0ab366c1d7edddc6e4d77357f44ada91d34b089d Mon Sep 17 00:00:00 2001 From: c-simpson Date: Wed, 28 Dec 2022 13:17:36 -0500 Subject: [PATCH] Support role names in user_update() --- .gitignore | 1 + src/server/api/user_api.py | 27 +++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 6ec237c0..9a6aa2a3 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,4 @@ start_env.sh .mypy_cache/ *secrets* *kustomization* +src/.venv/ \ No newline at end of file diff --git a/src/server/api/user_api.py b/src/server/api/user_api.py index 067803ea..14bac01c 100644 --- a/src/server/api/user_api.py +++ b/src/server/api/user_api.py @@ -396,6 +396,7 @@ def user_update(): if not update_dict: + logger.debug("Update called with nothing to update") return jsonify("No changed items specified") # If nothing to do, declare victory if "password" in update_dict.keys(): @@ -406,7 +407,6 @@ def user_update(): return jsonify("Password too weak") - # We have a variable number of columns to update. # We could generate a text query on the fly, but this seems the perfect place to use the ORM # and let it handle the update for us. @@ -419,10 +419,29 @@ def user_update(): session = Session() # #TODO: Figure out why context manager doesn't work or do try/finally - PU = Table("pdp_users", metadata, autoload=True, autoload_with=engine) - # pr = Table("pdp_user_roles", metadata, autoload=True, autoload_with=engine) + pr = Table("pdp_user_roles", metadata, autoload=True, autoload_with=engine) + + if ("role" in update_dict.keys()): # We are changing the role + + # Build dict of roles {name: id} + role_dict = {} + r = select((pr.c.role, pr.c._id)) + rr = session.execute(r) + fa = rr.fetchall() + for row in fa: + role_dict[row[0]] = row[1] - #TODO: Check tendered role or join roles table for update + logger.debug("Found %d roles", len(role_dict)) + # Replace the role name with the corresponding id for update + try: + # We could verify that the role is actually different - doesn't seem worth the effort + update_dict["role"] = role_dict[update_dict["role"]] + except KeyError: + logger.error("Attempted to change user '%s' to invalid role '%s'", username, update_dict["role"]) + session.close() + return jsonify("Invalid role specified"), 400 + + PU = Table("pdp_users", metadata, autoload=True, autoload_with=engine) stmt = update(PU).where(PU.columns.username == username).values(update_dict).\ execution_options(synchronize_session="fetch")