system_config.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from typing import Any, List
  2. from fastapi import APIRouter, Depends, HTTPException
  3. from sqlalchemy.orm import Session
  4. from app.api.v1 import deps
  5. from app.models.user import User, UserRole
  6. from app.schemas.system_config import SystemConfig, SystemConfigUpdate, SystemConfigCreate
  7. from app.services.system_config_service import SystemConfigService
  8. router = APIRouter()
  9. @router.get("/", response_model=List[SystemConfig], summary="获取所有系统配置")
  10. def read_system_configs(
  11. db: Session = Depends(deps.get_db),
  12. current_user: User = Depends(deps.get_current_active_user),
  13. ) -> Any:
  14. """
  15. 获取所有系统配置。
  16. 需要超级管理员权限。
  17. """
  18. if current_user.role != UserRole.SUPER_ADMIN:
  19. raise HTTPException(status_code=403, detail="权限不足")
  20. return SystemConfigService.get_all_configs(db)
  21. @router.post("/", response_model=SystemConfig, summary="设置系统配置")
  22. def update_system_config(
  23. config_in: SystemConfigCreate,
  24. db: Session = Depends(deps.get_db),
  25. current_user: User = Depends(deps.get_current_active_user),
  26. ) -> Any:
  27. """
  28. 创建或更新系统配置。
  29. 需要超级管理员权限。
  30. """
  31. if current_user.role != UserRole.SUPER_ADMIN:
  32. raise HTTPException(status_code=403, detail="权限不足")
  33. config = SystemConfigService.set_config(db, config_in.key, config_in.value, config_in.description)
  34. return config
  35. @router.get("/public", response_model=List[SystemConfig], summary="获取公开系统配置")
  36. def read_public_system_configs(
  37. db: Session = Depends(deps.get_db),
  38. ) -> Any:
  39. """
  40. 获取公开的系统配置(如登录开关状态)。
  41. 无需鉴权。
  42. """
  43. # Define which keys are public
  44. public_keys = ["sms_login_pc_enabled", "sms_login_mobile_enabled"]
  45. configs = []
  46. for key in public_keys:
  47. val = SystemConfigService.get_config(db, key)
  48. # Defaults to 'false' if not set
  49. if val is None:
  50. val = "false"
  51. configs.append({"key": key, "value": val, "description": "Public Config", "id": 0}) # Dummy ID for schema compliance if needed or handle better
  52. return configs