From 7977460d85bd93cc904f69c39ff922a78c6c84bf Mon Sep 17 00:00:00 2001 From: Alix JEUDI--LEMOINE Date: Wed, 5 Feb 2025 11:30:11 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Test=20if=20user=20exists=20&=20if?= =?UTF-8?q?=20already=20friends=20before=20creating=20friend=20request?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/routes/friends.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/routes/friends.py b/app/routes/friends.py index e9b9f3f..c7fb33d 100644 --- a/app/routes/friends.py +++ b/app/routes/friends.py @@ -44,7 +44,6 @@ async def get_friend(id: str, current_user: User = Depends(get_current_user)): responses={401: {"model": HTTPError}, 409: {"model": HTTPError}} ) async def add_friend(friend_to_add: FriendAddDTO, current_user: User = Depends(get_current_user)): - # TODO: test if exists friend: Friend = friend_to_add.model_dump() if(current_user.uid == friend["friend_user_id"]): @@ -52,6 +51,20 @@ async def add_friend(friend_to_add: FriendAddDTO, current_user: User = Depends(g status_code=status.HTTP_409_CONFLICT, detail="Cannot add yourself as a friend" ) + + # Test if already friends + if friends_collection.find_one({"user_id": current_user.uid, "friend_user_id": friend["friend_user_id"]}) is not None: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Friend already exists" + ) + + # Test if user exists + if db["users"].find_one({"_id": ObjectId(friend["friend_user_id"])}): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) friend["user_id"] = current_user.uid friend["status"] = "pending"