Spaces:
Sleeping
Sleeping
Download app/api/admin.py from yabeskn/briga-core-api: direct link, hf CLI and curl.
- Browser
- Download file 3.87 kB
-
https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/api/admin.py
- Command line
-
hf download hf://spaces/yabeskn/briga-core-api/app/api/admin.py
-
curl -L -o admin.py https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/api/admin.py
3.87 kB
| from fastapi import APIRouter, Depends, Request, HTTPException | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, update | |
| from datetime import datetime, timezone | |
| from loguru import logger | |
| from app.database import get_db | |
| from app.models.system import WorkflowConfig, ActivityLog | |
| router = APIRouter(prefix="/v1/admin", tags=["Admin"]) | |
| def _ensure_admin(request: Request): | |
| """Enforce admin role requirement.""" | |
| role = getattr(request.state, "user_role", None) | |
| if role not in ("admin", "ADMIN"): | |
| raise HTTPException(status_code=403, detail="Admin role required") | |
| async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig: | |
| """Fetch a workflow by name or raise 404.""" | |
| result = await db.execute( | |
| select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name) | |
| ) | |
| row = result.scalar_one_or_none() | |
| if row is None: | |
| raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found") | |
| return row | |
| async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str): | |
| """Record an activity log entry. Errors are logged but do not fail the request.""" | |
| try: | |
| log = ActivityLog( | |
| actor=getattr(request.state, 'user_email', None) or 'system', | |
| action=action, | |
| log_metadata=metadata, | |
| ) | |
| db.add(log) | |
| await db.commit() | |
| except Exception as e: | |
| logger.warning(f"Failed to log activity '{action}': {e}") | |
| try: | |
| await db.rollback() | |
| except Exception: | |
| pass | |
| async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)): | |
| _ensure_admin(request) | |
| result = await db.execute(select(WorkflowConfig)) | |
| rows = result.scalars().all() | |
| return [ | |
| { | |
| "workflow_name": r.workflow_name, | |
| "is_active": r.is_active, | |
| "schedule_cron": r.schedule_cron, | |
| "last_run": r.last_run, | |
| "updated_at": r.updated_at, | |
| } | |
| for r in rows | |
| ] | |
| async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)): | |
| _ensure_admin(request) | |
| await _get_workflow_or_404(workflow_name, db) | |
| # Only allow specific fields | |
| allowed = {"is_active", "schedule_cron"} | |
| update_values = {k: v for k, v in payload.items() if k in allowed} | |
| if not update_values: | |
| raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron") | |
| update_values["updated_at"] = datetime.now(timezone.utc) | |
| stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values) | |
| await db.execute(stmt) | |
| await db.commit() | |
| await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values)) | |
| return {"success": True, "updated": update_values} | |
| async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)): | |
| _ensure_admin(request) | |
| await _get_workflow_or_404(workflow_name, db) | |
| # Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event. | |
| stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)}) | |
| await db.execute(stmt) | |
| await db.commit() | |
| await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel") | |
| return {"success": True, "message": "Workflow run recorded (manual trigger)."} | |