25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 

45 satır
1.6 KiB

  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