Spaces:
Sleeping
Sleeping
Download app/api/v1/admin.py from baljot07/studiq-backend: direct link, hf CLI and curl.
- Browser
- Download file 6.12 kB
-
https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/app/api/v1/admin.py
- Command line
-
hf download hf://spaces/baljot07/studiq-backend/app/api/v1/admin.py
-
curl -L -o admin.py https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/app/api/v1/admin.py
6.12 kB
| """Secure administrative endpoints for managing system configurations, users, and documents. | |
| Restricted exclusively to admin users via OAuth email verification or database role. | |
| """ | |
| from fastapi import APIRouter, Depends, HTTPException, Query, Request | |
| from pydantic import BaseModel, Field | |
| from typing import Optional | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, func, delete | |
| import uuid | |
| from app.core.dependencies import get_current_admin | |
| from app.database import get_db | |
| from app.models.user import User | |
| from app.models.user_document import UserDocument | |
| from app.config import settings | |
| router = APIRouter(prefix="/admin", tags=["admin"]) | |
| class AdminConfigRequest(BaseModel): | |
| """Configuration structure for AI and search providers.""" | |
| tavily_api_key: Optional[str] = Field(default=None, max_length=200) | |
| serpapi_api_key: Optional[str] = Field(default=None, max_length=200) | |
| fireworks_api_key: Optional[str] = Field(default=None, max_length=200) | |
| gemini_api_key: Optional[str] = Field(default=None, max_length=200, description="Vision OCR and doubt solver") | |
| async def get_system_status( | |
| admin: User = Depends(get_current_admin), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| """Retrieve system states, document counts, and configuration health.""" | |
| try: | |
| user_files_count = (await db.execute(select(func.count(UserDocument.id)))).scalar() or 0 | |
| total_users_count = (await db.execute(select(func.count(User.id)))).scalar() or 0 | |
| except Exception: | |
| user_files_count = 0 | |
| total_users_count = 0 | |
| config = { | |
| "tavily_configured": bool(settings.tavily_api_key), | |
| "serpapi_configured": bool(settings.serpapi_api_key), | |
| "fireworks_configured": bool(settings.fireworks_api_key), | |
| "gemini_configured": bool(settings.gemini_api_key), | |
| "admin_email": settings.admin_email, | |
| } | |
| status = { | |
| "status": "ACTIVE", | |
| "current_task": "System operational. Real-time study assistant ready.", | |
| "total_files_processed": user_files_count, | |
| "total_users": total_users_count, | |
| "db_total_files": user_files_count, | |
| "db_total_chunks": 0, | |
| "storage_used_bytes": 0, | |
| "active_topic": None, | |
| } | |
| return { | |
| "agent": status, | |
| "config": config, | |
| } | |
| async def update_system_config( | |
| body: AdminConfigRequest, | |
| admin: User = Depends(get_current_admin), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| """Dynamically modify API credentials and persist them to PostgreSQL.""" | |
| from app.models.system_setting import SystemSetting | |
| if body.tavily_api_key is not None: | |
| val = body.tavily_api_key.strip() | |
| settings.tavily_api_key = val | |
| stmt = select(SystemSetting).where(SystemSetting.key == "tavily_api_key") | |
| res = await db.execute(stmt) | |
| setting = res.scalar_one_or_none() | |
| if setting: | |
| setting.value = val | |
| else: | |
| db.add(SystemSetting(key="tavily_api_key", value=val)) | |
| if body.serpapi_api_key is not None: | |
| val = body.serpapi_api_key.strip() | |
| settings.serpapi_api_key = val | |
| stmt = select(SystemSetting).where(SystemSetting.key == "serpapi_api_key") | |
| res = await db.execute(stmt) | |
| setting = res.scalar_one_or_none() | |
| if setting: | |
| setting.value = val | |
| else: | |
| db.add(SystemSetting(key="serpapi_api_key", value=val)) | |
| if body.fireworks_api_key is not None: | |
| val = body.fireworks_api_key.strip() | |
| settings.fireworks_api_key = val | |
| stmt = select(SystemSetting).where(SystemSetting.key == "fireworks_api_key") | |
| res = await db.execute(stmt) | |
| setting = res.scalar_one_or_none() | |
| if setting: | |
| setting.value = val | |
| else: | |
| db.add(SystemSetting(key="fireworks_api_key", value=val)) | |
| if body.gemini_api_key is not None: | |
| val = body.gemini_api_key.strip() | |
| settings.gemini_api_key = val | |
| stmt = select(SystemSetting).where(SystemSetting.key == "gemini_api_key") | |
| res = await db.execute(stmt) | |
| setting = res.scalar_one_or_none() | |
| if setting: | |
| setting.value = val | |
| else: | |
| db.add(SystemSetting(key="gemini_api_key", value=val)) | |
| await db.commit() | |
| return {"message": "Configurations updated and persisted successfully."} | |
| async def list_all_documents( | |
| admin: User = Depends(get_current_admin), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| """Retrieve all user documents in the system for administrative management.""" | |
| stmt_docs = select(UserDocument).order_by(UserDocument.created_at.desc()) | |
| result_docs = await db.execute(stmt_docs) | |
| docs = result_docs.scalars().all() | |
| documents_list = [ | |
| { | |
| "id": str(doc.id), | |
| "user_id": str(doc.user_id), | |
| "file_name": doc.file_name, | |
| "gdrive_file_id": doc.gdrive_file_id, | |
| "file_size": doc.file_size, | |
| "doc_type": doc.doc_type, | |
| "created_at": doc.created_at.isoformat() if doc.created_at else None, | |
| } | |
| for doc in docs | |
| ] | |
| return {"documents": documents_list} | |
| async def admin_delete_document( | |
| doc_id: str, | |
| admin: User = Depends(get_current_admin), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| """Delete a user document by ID.""" | |
| try: | |
| uuid_obj = uuid.UUID(doc_id) | |
| except ValueError: | |
| raise HTTPException(status_code=400, detail="Invalid document ID format") | |
| stmt = select(UserDocument).where(UserDocument.id == uuid_obj) | |
| res = await db.execute(stmt) | |
| doc = res.scalar_one_or_none() | |
| if not doc: | |
| raise HTTPException(status_code=404, detail="Document not found") | |
| await db.execute(delete(UserDocument).where(UserDocument.id == uuid_obj)) | |
| await db.commit() | |
| return {"status": "success", "message": "Document deleted successfully."} | |