Files
drb-core-server/app/internal/auth_wrappers.py
2025-05-26 02:36:21 -04:00

77 lines
2.8 KiB
Python

# internal/auth_wrappers.py
import os
import asyncio
from uuid import uuid4
from typing import Optional, List, Dict, Any
from internal.db_handler import MongoHandler #
from internal.types import User, UserRoles
DB_NAME = os.getenv("DB_NAME", "default_db")
MONGO_URL = os.getenv("MONGO_URL", "mongodb://10.10.202.4:27017/")
USER_DB_COLLECTION_NAME = "users"
class UserDbController:
def __init__(self):
self.db_h = MongoHandler(DB_NAME, USER_DB_COLLECTION_NAME, MONGO_URL) #
async def close_db_connection(self):
"""Closes the underlying MongoDB connection."""
if self.db_h:
await self.db_h.close_client() #
async def create_user(self, user_data: Dict[str, Any]) -> Optional[User]:
try:
if not user_data.get("_id"):
user_data['_id'] = str(uuid4())
inserted_id = None
async with self.db_h as db: #
insert_result = await db.insert_one(user_data) #
inserted_id = insert_result.inserted_id
if inserted_id:
query = {"_id": inserted_id}
inserted_doc = None
async with self.db_h as db: #
inserted_doc = await db.find_one(query) #
if inserted_doc:
return User.from_dict(inserted_doc)
return None
except Exception as e:
print(f"Create user failed: {e}")
return None
async def find_user(self, query: Dict[str, Any]) -> Optional[User]:
try:
found_doc = None
async with self.db_h as db: #
# The 'db' here is self.db_h, which is an instance of MongoHandler.
# MongoHandler.find_one will be called.
found_doc = await db.find_one(query) #
if found_doc:
return User.from_dict(found_doc)
return None
except Exception as e:
print(f"Find user failed: {e}") # This error should be less frequent or indicate actual DB issues now
return None
async def update_user(self, query: Dict[str, Any], update_data: Dict[str, Any]) -> Optional[int]:
try:
update_result = None
async with self.db_h as db: #
update_result = await db.update_one(query, update_data) #
return update_result.modified_count
except Exception as e:
print(f"Update user failed: {e}")
return None
async def delete_user(self, query: Dict[str, Any]) -> Optional[int]:
try:
delete_result = None
async with self.db_h as db: #
delete_result = await db.delete_one(query) #
return delete_result.deleted_count
except Exception as e:
print(f"Delete user failed: {e}")
return None