From 9f6aa38925ea2b484843e2157952f266d721d4fa Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Sat, 18 Dec 2021 01:52:35 +0100 Subject: [PATCH] fix(users): Reduce amount of SELECT queries in set_roles --- flaschengeist/controller/userController.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/flaschengeist/controller/userController.py b/flaschengeist/controller/userController.py index e5514cf..c2ca7f2 100644 --- a/flaschengeist/controller/userController.py +++ b/flaschengeist/controller/userController.py @@ -90,15 +90,13 @@ def update_user(user): db.session.commit() -def set_roles(user: User, roles: list[str], create=False): - user.roles_.clear() - for role_name in roles: - role = Role.query.filter(Role.name == role_name).one_or_none() - if not role: - if not create: - raise BadRequest("Role not found >{}<".format(role_name)) - role = Role(name=role_name) - user.roles_.append(role) +def set_roles(user: User, roles: list[str]): + if not isinstance(roles, list) and any([not isinstance(r, str) for r in roles]): + raise BadRequest("Invalid role name") + fetched = Role.query.filter(Role.name.in_(roles)).all() + if len(fetched) < len(roles): + raise BadRequest("Invalid role name, role not found") + user.roles_ = fetched def modify_user(user, password, new_password=None):