From a84d46aca1dc4e0cff2f00b19d30cad136ffd63b Mon Sep 17 00:00:00 2001 From: Guillaume Tucker Date: Fri, 10 Nov 2023 17:15:04 +0100 Subject: [PATCH] api.main: only look for duplicate user when required Only look up if another user already exists if the update contains a username and it's not already the same one as the initial user. This avoids unnecessary errors when updating a user entry with the same username and avoids database lookups with a username set to None. Signed-off-by: Guillaume Tucker --- api/main.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/api/main.py b/api/main.py index 3faa63cf..5533fcfd 100644 --- a/api/main.py +++ b/api/main.py @@ -220,12 +220,13 @@ async def update_me(request: Request, user: UserUpdate, Custom user update router handler will only allow users to update its own profile. Adding itself to 'admin' group is not allowed. """ - existing_user = await db.find_one(User, username=user.username) - if existing_user: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Username already exists", - ) + if user.username and user.username != current_user.username: + existing_user = await db.find_one(User, username=user.username) + if existing_user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Username already exists: {user.username}", + ) groups = [] if user.groups: for group_name in user.groups: @@ -251,7 +252,6 @@ async def update_me(request: Request, user: UserUpdate, async def update_user(user_id: str, request: Request, user: UserUpdate, current_user: User = Depends(get_current_superuser)): """Router to allow admin users to update other user account""" - user_from_id = await db.find_by_id(User, user_id) if not user_from_id: raise HTTPException( @@ -259,12 +259,13 @@ async def update_user(user_id: str, request: Request, user: UserUpdate, detail=f"User not found with id: {user_id}", ) - existing_user = await db.find_one(User, username=user.username) - if existing_user: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Username already exists", - ) + if user.username and user.username != user_from_id.username: + existing_user = await db.find_one(User, username=user.username) + if existing_user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Username already exists: {user.username}", + ) groups = [] if user.groups: