60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
from fastapi import FastAPI, status, HTTPException, Depends, APIRouter
|
|
from sqlalchemy.orm import Session
|
|
from .. import models, schemas, security, utils
|
|
from ..database import get_db
|
|
|
|
router = APIRouter(
|
|
prefix="/users",
|
|
tags=['Users']
|
|
)
|
|
|
|
@router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.User)
|
|
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
|
|
|
|
existing_user = db.query(models.Users).filter(models.Users.Email == user.Email).first()
|
|
if existing_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="User with this email already exists"
|
|
)
|
|
|
|
hashed_password = utils.hash(user.Hashed_password)
|
|
|
|
user_data = user.model_dump()
|
|
user_data["Hashed_password"] = hashed_password
|
|
|
|
new_user = models.Users(**user_data)
|
|
|
|
db.add(new_user)
|
|
db.commit()
|
|
db.refresh(new_user)
|
|
|
|
return new_user
|
|
|
|
|
|
@router.put("/{email}", response_model=schemas.User)
|
|
def update_user(email: str, updated_user: schemas.UserUpdate, db: Session = Depends(get_db), current_user: models.Users = Depends(security.get_current_user)):
|
|
|
|
if current_user.Email != email:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
|
|
|
existing_user = db.query(models.Users).filter(models.Users.Email == email).first()
|
|
if not existing_user:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
|
|
|
if updated_user.Email:
|
|
email_user = db.query(models.Users).filter(models.Users.Email == updated_user.Email).first()
|
|
if email_user and email_user.Email != email:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already in use")
|
|
|
|
if updated_user.Hashed_password:
|
|
hashed_password = utils.hash(updated_user.Hashed_password)
|
|
updated_user.Hashed_password = hashed_password
|
|
|
|
for key, value in updated_user.model_dump(exclude_unset=True).items():
|
|
setattr(existing_user, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(existing_user)
|
|
|
|
return existing_user |