Skip to content

Commit

Permalink
api.main: only look for duplicate user when required
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
gctucker authored and JenySadadia committed Nov 16, 2023
1 parent 00b2703 commit a84d46a
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -251,20 +252,20 @@ 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(
status_code=status.HTTP_404_NOT_FOUND,
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:
Expand Down

0 comments on commit a84d46a

Please sign in to comment.