From adeac8cbacbc0db40ac0a2c6c1ef059144887c73 Mon Sep 17 00:00:00 2001 From: Jeny Sadadia Date: Thu, 14 Sep 2023 22:43:29 +0530 Subject: [PATCH] api.main: add PUT '/user/' endpoint Implement handler to update user models. Only admin users will be allowed to access this endpoint and be able to update other user models. All user fields except password can be updated using this handler. Signed-off-by: Jeny Sadadia --- api/main.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/api/main.py b/api/main.py index 0030c5fe..1963d4f6 100644 --- a/api/main.py +++ b/api/main.py @@ -272,6 +272,45 @@ async def put_user_profile( return obj +@app.put('/user/{username}', response_model=User, + response_model_by_alias=False) +async def put_user( + username: str, + email: str = None, + groups: List[str] = Query([]), + current_user: User = Security(get_user, scopes=["admin"])): + """Update user model + Allow admin users to update all user fields except password""" + user = await db.find_one_by_attributes( + User, {'profile.username': username}) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"User not found with username: {username}" + ) + group_obj = [] + if groups: + for group_name in groups: + group = await db.find_one(UserGroup, name=group_name) + if not group: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"User group does not exist with name: \ +{group_name}") + group_obj.append(group) + obj = await db.update(User( + id=user.id, + profile=UserProfile( + username=username, + hashed_password=user.profile.hashed_password, + email=email if email else user.profile.email, + groups=group_obj if group_obj else user.profile.groups + ))) + await pubsub.publish_cloudevent('user', {'op': 'updated', + 'id': str(obj.id)}) + return obj + + @app.post('/group', response_model=UserGroup, response_model_by_alias=False) async def post_user_group( group: UserGroup,