diff --git a/app/routers/users.py b/app/routers/users.py index 48c3d83..f97970c 100644 --- a/app/routers/users.py +++ b/app/routers/users.py @@ -2,7 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from ..dependencies import users_active, permissions_checker, database from ..models import users from typing import Annotated - +from bson import ObjectId router = APIRouter() @@ -21,6 +21,33 @@ async def read_users(authorize: Annotated[bool, Depends(permissions_checker.Perm listUsers.append(user) return listUsers +@router.get("/users/search", tags=["users"], response_model=list[users.UserOut]) +async def read_users_id(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20, key: str | None = None, value: str | None= None): + if limit < 1 or skip < 0 or limit < skip: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="skip should be greater than 0 and limit should be greater than 1. Limit should be greater than skip" + ) + if key is None or value is None: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Key or/and value parameter is empty" + ) + limit = limit + skip + listUsers = [] + user_repository = users.UserRepository(database=database.database) + for user_index in user_repository.find_by({key: {'$regex': value}}, limit=limit, skip=skip): + user = users.UserOut(id=user_index.id, username=user_index.username, disabled=user_index.disabled, roles=user_index.roles) + listUsers.append(user) + return listUsers + + @router.get("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["password"]) async def read_users_me(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]): - return current_user \ No newline at end of file + return current_user + +@router.get("/users/{item_id}", tags=["users"], response_model=users.User) +async def read_users_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]): + user_repository = users.UserRepository(database=database.database) + user = user_repository.find_one_by_id(ObjectId(item_id)) + return user