"""管理员后台:用户管理 / 权限开关 / 渠道分配 / 站点概览""" from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from ...db.session import get_db from ...db import repos from ...models.entities import User, Channel, ChatSession from ...api.routers.auth import current_user from ...core import security router = APIRouter(prefix="/admin", tags=["admin"]) async def require_admin(user: User = Depends(current_user)): if not user.is_admin: raise HTTPException(403, "需要管理员权限") return user @router.get("/settings") async def get_settings(db=Depends(get_db), _: User = Depends(require_admin)): return await repos.SettingRepo.all(db) @router.post("/settings") async def set_setting(key: str, value: str, db=Depends(get_db), _: User = Depends(require_admin)): allowed = {"allow_register", "allow_delete_account", "allow_byok", "admin_data_visible"} if key not in allowed: raise HTTPException(400, "未知开关") await repos.SettingRepo.set(db, key, "true" if value == "true" else "false") return {"ok": True} @router.get("/users") async def list_users(db=Depends(get_db), _: User = Depends(require_admin)): users = await repos.UserRepo.all(db) n_sessions = len((await db.execute( __import__("sqlalchemy").select(ChatSession))).scalars().all()) return {"users": [{"id": u.id, "username": u.username, "is_admin": u.is_admin, "is_active": u.is_active} for u in users], "stats": {"users": len(users), "sessions": n_sessions}} class UserPatch(BaseModel): is_active: bool | None = None is_admin: bool | None = None new_password: str | None = None @router.patch("/users/{uid}") async def patch_user(uid: int, body: UserPatch, db=Depends(get_db), _: User = Depends(require_admin)): u = await repos.UserRepo.by_id(db, uid) if not u: raise HTTPException(404, "用户不存在") if body.is_active is not None: u.is_active = body.is_active if body.is_admin is not None: u.is_admin = body.is_admin if body.new_password: u.password_hash = security.hash_password(body.new_password) security.key_cache.pop(uid, None) await db.commit() return {"ok": True} class AuthInLike(BaseModel): username: str password: str @router.post("/users") async def create_user(body: AuthInLike, db=Depends(get_db), _: User = Depends(require_admin)): if await repos.UserRepo.by_username(db, body.username): raise HTTPException(409, "用户名已存在") salt = security.os.urandom(16) db.add(User(username=body.username, password_hash=security.hash_password(body.password), kdf_salt=salt.hex())) await db.commit() return {"ok": True} @router.post("/channels/{cid}/grant/{uid}") async def grant_channel(cid: int, uid: int, db=Depends(get_db), _: User = Depends(require_admin)): db.add(__import__("app.models.entities", fromlist=["ChannelGrant"]).ChannelGrant( channel_id=cid, user_id=uid)) await db.commit() return {"ok": True} @router.delete("/channels/{cid}/grant/{uid}") async def revoke_channel(cid: int, uid: int, db=Depends(get_db), _: User = Depends(require_admin)): from ...models.entities import ChannelGrant from sqlalchemy import delete as _del await db.execute(_del(ChannelGrant).where( ChannelGrant.channel_id == cid, ChannelGrant.user_id == uid)) await db.commit() return {"ok": True} @router.get("/channels/{cid}/grants") async def list_grants(cid: int, db=Depends(get_db), _: User = Depends(require_admin)): from ...models.entities import ChannelGrant rows = (await db.execute(__import__("sqlalchemy").select(ChannelGrant).where( ChannelGrant.channel_id == cid))).scalars().all() return {"user_ids": [r.user_id for r in rows]}