admin / Apex
publicBid Management and Orchestration Tool with AI Capability
Apex / Synapse-Apexv2 / backend / app / routers / admin.py
9589 B · main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import select from sqlalchemy.orm import Session from app.core.database import get_db from app.core.deps import audit, require_roles from app.core.security import hash_password from app.models import ( ALL_ROLES, ROLE_ADMIN, ROLE_BID_MANAGER, ROLE_FINANCE, AuditLog, ComplianceFramework, EffortRule, SystemSetting, User, WorkflowTemplate, ) from app.schemas import ( EffortRuleIn, EffortRuleOut, FrameworkIn, FrameworkOut, UserCreate, UserOut, UserUpdate, ) router = APIRouter(prefix="/api/admin", tags=["admin"]) admin_only = require_roles(ROLE_ADMIN) # --- users --- @router.get("/users", response_model=list[UserOut]) def list_users(db: Session = Depends(get_db), _: User = Depends(admin_only)): return db.execute(select(User).order_by(User.id)).scalars().all() @router.post("/users", response_model=UserOut, status_code=201) def create_user(body: UserCreate, db: Session = Depends(get_db), actor: User = Depends(admin_only)): if db.execute(select(User).where(User.email == body.email)).scalar_one_or_none(): raise HTTPException(status.HTTP_409_CONFLICT, "Email already exists") for r in body.roles: if r not in ALL_ROLES: raise HTTPException(status.HTTP_400_BAD_REQUEST, f"Unknown role {r}") user = User( email=body.email, name=body.name, roles=body.roles, password_hash=hash_password(body.password), must_change_password=True, ) db.add(user) db.commit() db.refresh(user) audit(db, actor, "user_created", "user", user.id, {"email": user.email, "roles": user.roles}) return user @router.patch("/users/{user_id}", response_model=UserOut) def update_user(user_id: int, body: UserUpdate, db: Session = Depends(get_db), actor: User = Depends(admin_only)): user = db.get(User, user_id) if not user: raise HTTPException(404, "User not found") if body.name is not None: user.name = body.name if body.roles is not None: if ROLE_ADMIN in user.roles and ROLE_ADMIN not in body.roles and _last_admin(db, user.id): raise HTTPException(400, "Cannot remove the last administrator") user.roles = body.roles if body.is_active is not None: if not body.is_active and ROLE_ADMIN in user.roles and _last_admin(db, user.id): raise HTTPException(400, "Cannot deactivate the last administrator") user.is_active = body.is_active if body.password: user.password_hash = hash_password(body.password) user.must_change_password = True db.commit() db.refresh(user) audit(db, actor, "user_updated", "user", user.id) return user @router.delete("/users/{user_id}") def delete_user(user_id: int, db: Session = Depends(get_db), actor: User = Depends(admin_only)): user = db.get(User, user_id) if not user: raise HTTPException(404, "User not found") if user.id == actor.id: raise HTTPException(400, "You cannot delete your own account") if ROLE_ADMIN in user.roles and _last_admin(db, user.id): raise HTTPException(400, "Cannot delete the last administrator") user.is_active = False # soft delete db.commit() audit(db, actor, "user_deleted", "user", user.id) return {"ok": True} def _last_admin(db: Session, exclude_id: int) -> bool: admins = db.execute(select(User).where(User.is_active == True)).scalars().all() # noqa: E712 remaining = [u for u in admins if ROLE_ADMIN in u.roles and u.id != exclude_id] return len(remaining) == 0 # --- MFA enforcement toggle --- @router.get("/settings/enforce-mfa") def get_enforce_mfa(db: Session = Depends(get_db), _: User = Depends(admin_only)): row = db.get(SystemSetting, "enforce_mfa") return {"enabled": bool(row and row.value.get("enabled"))} @router.put("/settings/enforce-mfa") def set_enforce_mfa(payload: dict, db: Session = Depends(get_db), actor: User = Depends(admin_only)): row = db.get(SystemSetting, "enforce_mfa") if not row: row = SystemSetting(key="enforce_mfa", value={}) db.add(row) row.value = {"enabled": bool(payload.get("enabled"))} db.commit() audit(db, actor, "enforce_mfa_set", "setting", "enforce_mfa", row.value) return row.value # --- AI Integration (Assistant) toggle --- @router.get("/settings/ai-assistant") def get_ai_assistant(db: Session = Depends(get_db), _: User = Depends(admin_only)): from app.core.config import settings row = db.get(SystemSetting, "ai_assistant") return {"enabled": bool(row and row.value.get("enabled")), "ai_key_present": settings.ai_enabled} @router.put("/settings/ai-assistant") def set_ai_assistant(payload: dict, db: Session = Depends(get_db), actor: User = Depends(admin_only)): row = db.get(SystemSetting, "ai_assistant") if not row: row = SystemSetting(key="ai_assistant", value={}) db.add(row) row.value = {"enabled": bool(payload.get("enabled"))} db.commit() audit(db, actor, "ai_assistant_set", "setting", "ai_assistant", row.value) return row.value # --- frameworks --- @router.get("/frameworks", response_model=list[FrameworkOut]) def list_frameworks(db: Session = Depends(get_db), _: User = Depends(admin_only)): return db.execute(select(ComplianceFramework).order_by(ComplianceFramework.name)).scalars().all() @router.post("/frameworks", response_model=FrameworkOut, status_code=201) def create_framework(body: FrameworkIn, db: Session = Depends(get_db), actor: User = Depends(admin_only)): fw = ComplianceFramework(**body.model_dump()) db.add(fw) db.commit() db.refresh(fw) audit(db, actor, "framework_created", "framework", fw.id) return fw @router.patch("/frameworks/{fw_id}", response_model=FrameworkOut) def update_framework(fw_id: int, body: FrameworkIn, db: Session = Depends(get_db), actor: User = Depends(admin_only)): fw = db.get(ComplianceFramework, fw_id) if not fw: raise HTTPException(404, "Not found") for k, v in body.model_dump().items(): setattr(fw, k, v) db.commit() db.refresh(fw) audit(db, actor, "framework_updated", "framework", fw.id) return fw @router.delete("/frameworks/{fw_id}") def delete_framework(fw_id: int, db: Session = Depends(get_db), actor: User = Depends(admin_only)): fw = db.get(ComplianceFramework, fw_id) if not fw: raise HTTPException(404, "Not found") db.delete(fw) db.commit() audit(db, actor, "framework_deleted", "framework", fw_id) return {"ok": True} # --- effort rules (Module 3 config) — Administrator, Bid Manager or Finance --- effort_editor = require_roles(ROLE_ADMIN, ROLE_BID_MANAGER, ROLE_FINANCE) @router.get("/effort-rules", response_model=list[EffortRuleOut]) def list_rules(db: Session = Depends(get_db), _: User = Depends(effort_editor)): return db.execute(select(EffortRule).order_by(EffortRule.id)).scalars().all() @router.post("/effort-rules", response_model=EffortRuleOut, status_code=201) def create_rule(body: EffortRuleIn, db: Session = Depends(get_db), actor: User = Depends(effort_editor)): rule = EffortRule(**body.model_dump()) db.add(rule) db.commit() db.refresh(rule) audit(db, actor, "effort_rule_created", "effort_rule", rule.id, {"name": rule.name}) return rule @router.patch("/effort-rules/{rule_id}", response_model=EffortRuleOut) def update_rule(rule_id: int, body: EffortRuleIn, db: Session = Depends(get_db), actor: User = Depends(effort_editor)): rule = db.get(EffortRule, rule_id) if not rule: raise HTTPException(404, "Not found") for k, v in body.model_dump().items(): setattr(rule, k, v) db.commit() db.refresh(rule) audit(db, actor, "effort_rule_updated", "effort_rule", rule.id, {"name": rule.name}) return rule @router.delete("/effort-rules/{rule_id}") def delete_rule(rule_id: int, db: Session = Depends(get_db), actor: User = Depends(effort_editor)): rule = db.get(EffortRule, rule_id) if rule: db.delete(rule) db.commit() audit(db, actor, "effort_rule_deleted", "effort_rule", rule_id) return {"ok": True} # --- workflow templates --- @router.get("/workflows") def list_workflows(db: Session = Depends(get_db), _: User = Depends(admin_only)): rows = db.execute(select(WorkflowTemplate)).scalars().all() return [{"id": w.id, "name": w.name, "is_default": w.is_default, "stages": w.stages, "milestones": w.milestones} for w in rows] @router.patch("/workflows/{wf_id}") def update_workflow(wf_id: int, payload: dict, db: Session = Depends(get_db), actor: User = Depends(admin_only)): wf = db.get(WorkflowTemplate, wf_id) if not wf: raise HTTPException(404, "Not found") for k in ("name", "stages", "milestones"): if k in payload: setattr(wf, k, payload[k]) db.commit() audit(db, actor, "workflow_updated", "workflow", wf.id) return {"id": wf.id, "name": wf.name, "stages": wf.stages, "milestones": wf.milestones} # --- audit log --- @router.get("/audit") def audit_log(limit: int = 200, db: Session = Depends(get_db), _: User = Depends(admin_only)): rows = db.execute(select(AuditLog).order_by(AuditLog.ts.desc()).limit(min(limit, 500))).scalars().all() return [ {"id": r.id, "ts": r.ts, "actor": r.actor, "action": r.action, "entity": r.entity, "entity_id": r.entity_id, "detail": r.detail} for r in rows ] |