from fastapi import APIRouter, Depends, HTTPException, status, Response from fastapi.responses import JSONResponse from datetime import datetime from ..dependencies import users_token, permissions_checker, database from ..models import users from pydantic import EmailStr from typing import Annotated from bson import ObjectId router = APIRouter() @router.get("/users", tags=["users"], response_model=list[users.UserOut]) async def read_users(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], skip: int = 0, limit: int = 20, id_user: str | None = None, roles: str | None = None, status: int | None = None, email: EmailStr | 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" ) limit = limit + skip listUsers = [] user_repository = users.UserRepository(database=database.database) object_search = {} if status is not None and roles is not None: object_search = {"$and":[{"roles":{"$eq": roles}}, {"status":{"$eq":status}}]} else: if status is not None: object_search = {"status":{"$eq": status}} if roles is not None: object_search = {"roles":{"$eq":roles}} if id_user is not None: userid = ObjectId(id_user) object_search = {"id": {"$regex": userid}} if status is not None and roles is not None: object_search = {"$and":[{"id":{"$regex": userid}}, {"roles":{"$eq": roles}}, {"status":{"$eq":status}}]} else: if status is not None: object_search = {"$and":[{"id":{"$regex": userid}}, {"status":{"$eq":status}}]} if roles is not None: object_search = {"$and":[{"id":{"$regex": userid}}, {"roles":{"$eq":roles}}]} if email is not None: object_search = {"email": {"$eq": email}} if status is not None and roles is not None: object_search = {"$and":[{"email":{"$eq": email}}, {"roles":{"$eq": roles}}, {"status":{"$eq":status}}]} else: if status is not None: object_search = {"$and":[{"email":{"$eq": email}}, {"status":{"$eq":status}}]} if roles is not None: object_search = {"$and":[{"email":{"$eq": email}}, {"roles":{"$eq":roles}}]} for user_index in user_repository.find_by(object_search, limit=limit, skip=skip): user = users.UserOut(id=user_index.id, username=user_index.username, email=user_index.email, status=user_index.status, roles=user_index.roles, firstName=user_index.firstName, name=user_index.name) listUsers.append(user) return listUsers @router.get("/users/search", tags=["users"], response_model=list[users.UserOut]) async def read_users_search(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20): 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, status=user_index.status, roles=user_index.roles, email=user_index.email, firstName=user_index.firstName, name=user_index.name) listUsers.append(user) return listUsers @router.get("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"]) async def read_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]): return current_user @router.get("/users/count", tags=["users"]) async def read_users_count(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]): count = database.database.get_collection("users").estimated_document_count() content = {"count":count} response = JSONResponse(content=content) return response @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 @router.delete("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"]) async def delete_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], remove: bool = False): user_repository = users.UserRepository(database=database.database) current_user.status = 0 if remove is True: current_user.status = -1 user_repository.save(current_user) return current_user @router.delete("/users/groups",tags=["users"]) async def delete_users_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove: bool = False, userids: list[str] = []): if len(userids) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="userids should be greater than 0" ) user_repository = users.UserRepository(database=database.database) content = {"roles":user.roles,"message": "users are disabled"} for i in userids: user = user_repository.find_one_by_id(ObjectId(i)) user.status = 0 if remove is True: user.status = -1 content = {"roles":user.roles,"message": "users are deleted "} user_repository.save(current_user) response = JSONResponse(content=content) return response @router.delete("/users/{item_id}", tags=["users"], response_model=users.User) async def delete_users_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove : bool = False): user_repository = users.UserRepository(database=database.database) user = user_repository.find_one_by_id(ObjectId(item_id)) user.status = 0 if remove is True: user.status = -1 user_repository.save(user) return user @router.put("/users/me",tags=["users"], response_model=users.User, response_model_exclude=["id", "password", "roles", "status"]) async def update_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], userSingle: users.UserIn | None = None): user_repository = users.UserRepository(database=database.database) current_user.username = userSingle.username current_user.password = user_token.get_password_hash(userSingle.password) current_user.roles = userSingle.roles current_user.email = userSingle.email user_repository.save(current_user) return current_user @router.put("/users", tags=["users"], response_model=users.User, status_code=status.HTTP_200_OK) async def update_users_id(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], userSingle: users.UserIn | None = None): if userSingle is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Body request is empty" ) user_repository = users.UserRepository(database=database.database) user = user_repository.find_one_by({"username": {'$eq': userSingle.username}}) if user is None: Response.status_code = status.HTTP_201_CREATED user = users.User(username=userSingle.username, password=users_token.get_password_hash(userSingle.password), email=userSingle.email) user.username = userSingle.username user.password = users_token.get_password_hash(userSingle.password) user.roles = userSingle.roles user.email = userSingle.email user.firstName = userSingle.firstName user.name = userSingle.name user.birth = userSingle.birth user.updated_at = datetime.today() user_repository.save(user) return user @router.patch("/users/groups",tags=["users"]) async def patch_users_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], userids: list[str] = []): if len(userids) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="userids should be greater than 0" ) user_repository = users.UserRepository(database=database.database) content = {"roles":user.roles,"message": "users are enabled"} for i in userids: user = user_repository.find_one_by_id(ObjectId(i)) user.status = 1 user_repository.save(current_user) response = JSONResponse(content=content) return response @router.patch("/users/{item_id}", tags=["users"], response_model=users.User) async def patch_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)) user.status = 1 user_repository.save(user) return user