From a6ca7a0134344fff748c6b315ae4b5963a20c63e Mon Sep 17 00:00:00 2001 From: Maria Ropat <35531751+Mropat@users.noreply.github.com> Date: Tue, 15 Mar 2022 14:33:51 +0100 Subject: [PATCH] Conflict when user added twice, delete user endpoint (#35)(minor) ### Added * Delete user endpoint * Change email endpoint to replace "Archive user cli" ### Fixed - Return 409 when trying to add existing user --- genotype_api/api/endpoints/users.py | 40 +++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/genotype_api/api/endpoints/users.py b/genotype_api/api/endpoints/users.py index 398db1b..a43efdb 100644 --- a/genotype_api/api/endpoints/users.py +++ b/genotype_api/api/endpoints/users.py @@ -1,8 +1,11 @@ """Routes for users""" -from typing import List +from typing import List, Optional from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import EmailStr +from starlette import status +from starlette.responses import JSONResponse from genotype_api.crud.users import get_user from genotype_api.database import get_session @@ -23,6 +26,39 @@ def read_user( return get_user(session=session, user_id=user_id) +@router.delete("/{user_id}") +def delete_user( + user_id: int, + session: Session = Depends(get_session), + current_user: User = Depends(get_active_user), +) -> JSONResponse: + + user: User = get_user(session=session, user_id=user_id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") + session.delete(user) + session.commit() + session.flush() + return JSONResponse(content="User deleted successfully", status_code=status.HTTP_200_OK) + + +@router.put("/{user_id}/email", response_model=User) +def change_user_email( + user_id: int, + email: EmailStr, + session: Session = Depends(get_session), + current_user: User = Depends(get_active_user), +) -> User: + user: User = get_user(session=session, user_id=user_id) + if not user: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") + user.email = email + session.add(user) + session.commit() + session.refresh(user) + return user + + @router.get("/", response_model=List[UserRead]) def read_users( skip: int = 0, @@ -42,7 +78,7 @@ def create_user( ): user_in_db: List[User] = session.exec(select(User).where(User.email == user.email)).all() if user_in_db: - raise HTTPException(status_code=400, detail="Email already registered") + raise HTTPException(status_code=409, detail="Email already registered") db_user = User.from_orm(user) session.add(db_user) session.commit()