94 lines
2.6 KiB
Python
94 lines
2.6 KiB
Python
# app/routers/settings.py
|
|
from typing import Dict
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from pydantic import BaseModel
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.models.setting import Setting
|
|
from app.models.admin import Admin
|
|
from app.auth import get_current_admin
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# Public settings keys that can be accessed without auth
|
|
PUBLIC_SETTINGS = [
|
|
"site_name", "site_logo", "site_favicon", "site_description",
|
|
"contact_phones", "contact_emails", "contact_address",
|
|
"social_links", "friend_links",
|
|
"copyright", "bottom_links",
|
|
"privacy_url", "terms_url", "sitemap_url",
|
|
"seo_title", "seo_description", "seo_keywords"
|
|
]
|
|
|
|
|
|
# Schemas
|
|
class SettingsUpdate(BaseModel):
|
|
settings: Dict[str, str]
|
|
|
|
|
|
class SettingsResponse(BaseModel):
|
|
code: int = 200
|
|
data: dict = None
|
|
message: str = "success"
|
|
|
|
|
|
# Helper
|
|
def get_setting_value(db: Session, key: str) -> str:
|
|
setting = db.query(Setting).filter(Setting.key == key).first()
|
|
return setting.value if setting else None
|
|
|
|
|
|
def set_setting_value(db: Session, key: str, value: str):
|
|
setting = db.query(Setting).filter(Setting.key == key).first()
|
|
if setting:
|
|
setting.value = value
|
|
else:
|
|
setting = Setting(key=key, value=value)
|
|
db.add(setting)
|
|
|
|
|
|
# Public routes
|
|
@router.get("/settings", response_model=SettingsResponse)
|
|
def get_public_settings(db: Session = Depends(get_db)):
|
|
"""Get public settings"""
|
|
result = {}
|
|
for key in PUBLIC_SETTINGS:
|
|
value = get_setting_value(db, key)
|
|
if value:
|
|
result[key] = value
|
|
return SettingsResponse(data=result)
|
|
|
|
|
|
# Admin routes
|
|
@router.get("/admin/settings", response_model=SettingsResponse)
|
|
def get_all_settings(
|
|
db: Session = Depends(get_db),
|
|
current_admin: Admin = Depends(get_current_admin)
|
|
):
|
|
"""Get all settings"""
|
|
settings = db.query(Setting).all()
|
|
result = {}
|
|
for s in settings:
|
|
result[s.key] = {
|
|
"value": s.value,
|
|
"group": s.group,
|
|
"description": s.description
|
|
}
|
|
return SettingsResponse(data=result)
|
|
|
|
|
|
@router.put("/admin/settings", response_model=SettingsResponse)
|
|
def update_settings(
|
|
request: SettingsUpdate,
|
|
db: Session = Depends(get_db),
|
|
current_admin: Admin = Depends(get_current_admin)
|
|
):
|
|
"""Batch update settings"""
|
|
for key, value in request.settings.items():
|
|
set_setting_value(db, key, value)
|
|
|
|
db.commit()
|
|
return SettingsResponse(message="设置更新成功")
|