Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 

158 lignes
5.1 KiB

  1. # Routes for user. MAIN PART OF THE API
  2. from math import ceil
  3. from fastapi import APIRouter, HTTPException, status, Query
  4. from sqlalchemy.orm import Session
  5. from sqlalchemy import or_
  6. from fastapi import Depends
  7. from typing import List, Annotated
  8. from apis.v1.route_auth import get_current_user
  9. from core.config import settings
  10. from db.models.user import User
  11. from schemas.user import UserCreate, ShowUser, ShowDriver, DriverCreate, OutputUser, UsersPage
  12. from db.session import get_db
  13. from db.repository.user import (
  14. create_new_user,
  15. list_users,
  16. get_user_by_id,
  17. replace_user_data,
  18. create_new_driver,
  19. delete_user_data,
  20. get_users_by_name
  21. )
  22. router = APIRouter()
  23. @router.post("/", response_model=ShowUser, status_code=status.HTTP_201_CREATED)
  24. def create_user(
  25. user: UserCreate,
  26. db: Session = Depends(get_db),
  27. current_user: User = Depends(get_current_user),
  28. ):
  29. if user.Role not in settings.ALLOWED_ROLES:
  30. raise HTTPException(
  31. status_code=400,
  32. detail=f"Role {user.Role} is not allowed. Allowed roles are {settings.ALLOWED_ROLES}",
  33. )
  34. if current_user.Role != "Admin":
  35. raise HTTPException(
  36. status_code=403, detail="You are not authorized to perform this action"
  37. )
  38. # if current_user.Role != "Admin":
  39. # raise HTTPException(status_code=403, detail="You are not authorized to perform this action")
  40. user = create_new_user(user=user, db=db)
  41. return user
  42. @router.post("/driver", response_model=ShowDriver, status_code=status.HTTP_201_CREATED)
  43. def create_driver(
  44. driver: DriverCreate,
  45. db: Session = Depends(get_db),
  46. current_user: User = Depends(get_current_user),
  47. ):
  48. if current_user.Role != "Admin":
  49. raise HTTPException(
  50. status_code=403, detail="You are not authorized to perform this action"
  51. )
  52. driver = create_new_driver(driver=driver, db=db)
  53. return driver
  54. @router.get("/", response_model=List[ShowUser], status_code=status.HTTP_200_OK)
  55. def get_all_users(db: Session = Depends(get_db), role: str = None):
  56. if role is None:
  57. users = list_users(db=db)
  58. return users
  59. users = list_users(db=db, role=role)
  60. return users
  61. @router.put("/{user_id}", response_model=ShowUser, status_code=status.HTTP_202_ACCEPTED)
  62. def update_user(
  63. user_id: int,
  64. user: UserCreate,
  65. db: Session = Depends(get_db),
  66. current_user: User = Depends(get_current_user),
  67. ):
  68. if current_user.Role != "Admin":
  69. raise HTTPException(
  70. status_code=403, detail="You are not authorized to perform this action"
  71. )
  72. user = replace_user_data(user_id=user_id, user_data=user, db=db)
  73. if user == "userNotFound":
  74. raise HTTPException(status_code=404, detail="User not found")
  75. return user
  76. @router.get("/me", response_model=ShowUser, status_code=status.HTTP_200_OK)
  77. def get_user_me(
  78. current_user: Annotated[User, Depends(get_current_user)],
  79. db: Annotated[Session, Depends(get_db)],
  80. ):
  81. print("Getting current user...")
  82. return current_user
  83. @router.get("/{user_id}", response_model=ShowUser, status_code=status.HTTP_200_OK)
  84. def get_user(user_id: int, db: Session = Depends(get_db)):
  85. user = get_user_by_id(user_id=user_id, role="Any", db=db)
  86. if not user:
  87. raise HTTPException(status_code=404, detail="User not found")
  88. return user
  89. @router.get(
  90. "/driver/{driver_id}", response_model=ShowDriver, status_code=status.HTTP_200_OK
  91. )
  92. def get_driver(driver_id: int, db: Session = Depends(get_db)):
  93. driver = get_user_by_id(user_id=driver_id, role="Driver", db=db)
  94. if not driver:
  95. raise HTTPException(status_code=404, detail="Driver not found")
  96. res = driver.__dict__
  97. res["AssignedVehicle"] = driver.vehicle
  98. return driver
  99. @router.delete("/{user_id}", status_code=status.HTTP_200_OK)
  100. def delete_user(
  101. user_id: int,
  102. db: Session = Depends(get_db),
  103. current_user: User = Depends(get_current_user),
  104. ):
  105. if current_user.Role != "Admin":
  106. raise HTTPException(
  107. status_code=403, detail="You are not authorized to perform this action"
  108. )
  109. result = delete_user_data(id=user_id, db=db)
  110. if result == "userNotFound":
  111. raise HTTPException(status_code=404, detail="User not found")
  112. return result
  113. @router.get("/search/", response_model=UsersPage)
  114. def search_users(db: Session = Depends(get_db), name: str = None, role: str = None, page: int = 1, per_page: int = 20):
  115. query = db.query(User).filter(User.Name.like(f"{name}%"))
  116. if role is not None and role != "Admin":
  117. query = query.filter(User.Role == role)
  118. total_users = query.count()
  119. total_pages = ceil(total_users / per_page)
  120. users = query.offset((page - 1) * per_page).limit(per_page).all()
  121. output_users = [OutputUser(
  122. id= user.Id,
  123. Name=user.Name,
  124. MiddleName = user.MiddleName,
  125. LastName=user.LastName,
  126. ContactNumber=user.ContactNumber,
  127. Address=user.Address,
  128. Email=user.Email,
  129. Role=user.Role,
  130. AssignedVehicle= None
  131. ) for user in users]
  132. return {"users": output_users, "total_pages": total_pages}