Files
openteam/server/internal/api/admin.go
T
SakurasanandClaude b365779188 模型限制: 系统配置全局开放/禁止 + 用户级限制 + 网关拦截
- User 新增 allowed_models/denied_models(用户级模型限制)
- 系统配置 model_allowlist/model_denylist 全局策略, 保存即时失效网关缓存
- 网关 checkModelAllowed: 用户级 > 全局(禁止命中→403, 白名单非空→仅白名单)
- 三个协议处理器均校验, 错误按客户端协议格式返回
- 配置页"模型限制"卡片(全局允许/禁止多选); 用户编辑支持允许/禁止模型

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-16 01:34:12 +08:00

231 lines
6.6 KiB
Go

package api
import (
"encoding/json"
"net/http"
"net/mail"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/openteam/server/internal/pkg/resp"
"github.com/openteam/server/internal/store"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// AdminUsers GET /api/v1/admin/users — 用户列表(搜索、分页)。
func (h *Handler) AdminUsers(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if size < 1 || size > 100 {
size = 20
}
q := h.a.DB.Model(&store.User{})
if kw := c.Query("q"); kw != "" {
q = q.Where("username LIKE ? OR email LIKE ?", "%"+kw+"%", "%"+kw+"%")
}
var total int64
q.Count(&total)
var users []store.User
q.Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&users)
out := make([]gin.H, 0, len(users))
for _, u := range users {
out = append(out, h.publicUser(&u))
}
resp.OK(c, gin.H{"items": out, "total": total, "page": page, "page_size": size})
}
// AdminPatchUser PATCH /api/v1/admin/users/:id — 角色/状态。
func (h *Handler) AdminPatchUser(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid user id")
return
}
var req struct {
Username *string `json:"username"`
Email *string `json:"email"`
Password *string `json:"password"`
Role *string `json:"role"`
Status *string `json:"status"`
AllowedModels *[]string `json:"allowed_models"`
DeniedModels *[]string `json:"denied_models"`
}
if err := c.ShouldBindJSON(&req); err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid input")
return
}
updates := map[string]any{}
if req.Username != nil {
u := strings.TrimSpace(*req.Username)
if len(u) < 3 || len(u) > 32 {
resp.Fail(c, http.StatusBadRequest, "username must be 3-32 chars")
return
}
var n int64
h.a.DB.Model(&store.User{}).Where("username = ? AND id != ?", u, id).Count(&n)
if n > 0 {
resp.Fail(c, http.StatusConflict, "username already taken")
return
}
updates["username"] = u
}
if req.Email != nil {
e := strings.ToLower(strings.TrimSpace(*req.Email))
if _, err := mail.ParseAddress(e); err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid email")
return
}
var n int64
h.a.DB.Model(&store.User{}).Where("email = ? AND id != ?", e, id).Count(&n)
if n > 0 {
resp.Fail(c, http.StatusConflict, "email already taken")
return
}
updates["email"] = e
}
if req.Password != nil && *req.Password != "" {
if len(*req.Password) < 8 {
resp.Fail(c, http.StatusBadRequest, "password must be at least 8 chars")
return
}
hash, err := h.a.Hasher.HashPassword(*req.Password)
if err != nil {
resp.Fail(c, http.StatusInternalServerError, "failed to hash password")
return
}
updates["password_hash"] = hash
}
if req.Role != nil {
if *req.Role != store.RoleUser && *req.Role != store.RoleAdmin {
resp.Fail(c, http.StatusBadRequest, "role must be user or admin")
return
}
updates["role"] = *req.Role
}
if req.Status != nil {
if *req.Status != store.UserStatusActive && *req.Status != store.UserStatusDisabled {
resp.Fail(c, http.StatusBadRequest, "status must be active or disabled")
return
}
updates["status"] = *req.Status
}
// 模型限制(jsonb):手动序列化
if req.AllowedModels != nil {
raw, _ := json.Marshal(*req.AllowedModels)
updates["allowed_models"] = string(raw)
}
if req.DeniedModels != nil {
raw, _ := json.Marshal(*req.DeniedModels)
updates["denied_models"] = string(raw)
}
if len(updates) == 0 {
resp.OK(c, gin.H{"ok": true})
return
}
res := h.a.DB.Model(&store.User{}).Where("id = ?", id).Updates(updates)
if res.Error != nil {
resp.Fail(c, http.StatusInternalServerError, "failed to update user")
return
}
if res.RowsAffected == 0 {
resp.Fail(c, http.StatusNotFound, "user not found")
return
}
resp.OK(c, gin.H{"ok": true})
}
// AdminAdjustBalance POST /api/v1/admin/users/:id/balance — 手动调余额(写流水)。
func (h *Handler) AdminAdjustBalance(c *gin.Context) {
admin := sessionUser(c)
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid user id")
return
}
var req struct {
Amount float64 `json:"amount" binding:"required"`
Remark string `json:"remark"`
}
if err := c.ShouldBindJSON(&req); err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid input: amount required")
return
}
if req.Amount == 0 {
resp.Fail(c, http.StatusBadRequest, "amount must not be zero")
return
}
err = h.a.DB.Transaction(func(tx *gorm.DB) error {
var u store.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&u, id).Error; err != nil {
return err
}
newBalance := u.Balance + req.Amount
if err := tx.Model(&store.User{}).Where("id = ?", id).Update("balance", newBalance).Error; err != nil {
return err
}
ref := "admin:" + strconv.FormatUint(u.ID, 10) + ":" + time.Now().Format("20060102150405")
_ = admin.ID // 流水里不冗余管理员 ID;需要时再加
return tx.Create(&store.BalanceLog{
UserID: u.ID,
Change: req.Amount,
BalanceAfter: newBalance,
Type: store.BalanceTypeAdminAdjust,
RefID: ref,
Remark: req.Remark,
}).Error
})
if err != nil {
resp.Fail(c, http.StatusNotFound, "user not found or failed to adjust")
return
}
resp.OK(c, gin.H{"ok": true})
}
// AdminConfig GET /api/v1/admin/config — 全部系统配置。
func (h *Handler) AdminConfig(c *gin.Context) {
var cfgs []store.SystemConfig
if err := h.a.DB.Find(&cfgs).Error; err != nil {
resp.Fail(c, http.StatusInternalServerError, "failed to load config")
return
}
out := gin.H{}
for _, cfg := range cfgs {
out[cfg.Key] = json.RawMessage(cfg.Value)
}
resp.OK(c, gin.H{"config": out})
}
// AdminPutConfig PUT /api/v1/admin/config — 整表覆盖(upsert)。
func (h *Handler) AdminPutConfig(c *gin.Context) {
var req map[string]json.RawMessage
if err := c.ShouldBindJSON(&req); err != nil {
resp.Fail(c, http.StatusBadRequest, "invalid input")
return
}
err := h.a.DB.Transaction(func(tx *gorm.DB) error {
for k, v := range req {
cfg := store.SystemConfig{Key: k, Value: string(v)}
if err := tx.Save(&cfg).Error; err != nil {
return err
}
}
return nil
})
if err != nil {
resp.Fail(c, http.StatusInternalServerError, "failed to save config")
return
}
// 模型限制等策略可能变化,立即失效缓存
if h.gw != nil {
h.gw.ResetModelPolicy()
}
resp.OK(c, gin.H{"ok": true})
}