Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

route_user.py 1.6 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Routes for user. MAIN PART OF THE API
  2. from fastapi import APIRouter, HTTPException, status
  3. from sqlalchemy.orm import Session
  4. from fastapi import Depends
  5. from typing import List, Annotated
  6. from apis.v1.route_auth import get_current_user
  7. from db.models.user import User
  8. from schemas.user import UserCreate, ShowUser
  9. from db.session import get_db
  10. from db.repository.user import create_new_user, list_users, get_user_by_id
  11. router = APIRouter()
  12. @router.post("/", response_model=ShowUser, status_code=status.HTTP_201_CREATED)
  13. def create_user(user: UserCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
  14. if current_user.Role != "Admin":
  15. raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
  16. user = create_new_user(user=user, db=db)
  17. return user
  18. @router.get("/", response_model=List[ShowUser], status_code=status.HTTP_200_OK)
  19. def get_all_users(db: Session = Depends(get_db), role: str = None):
  20. if role is None:
  21. users = list_users(db=db)
  22. return users
  23. users = list_users(db=db, role=role)
  24. return users
  25. @router.get("/me", response_model=ShowUser, status_code=status.HTTP_200_OK)
  26. def get_user_me(current_user: Annotated[User, Depends(get_current_user)], db: Annotated[Session, Depends(get_db)]):
  27. print("Getting current user...")
  28. return current_user
  29. @router.get("/{user_id}", response_model=ShowUser, status_code=status.HTTP_200_OK)
  30. def get_user(user_id: int, db: Session = Depends(get_db)):
  31. user = get_user_by_id(user_id=user_id, db=db)
  32. if not user:
  33. raise HTTPException(status_code=404, detail="User not found")
  34. return user