- 计费:19 个金额字段 float64→decimal.Decimal,DB 列保持 numeric(20,8) 零迁移; API 金额仍为 JSON number(MarshalJSONWithoutQuotes),前端零改动 - failover:保留时间预算,新增 OT_PROXY_FAILOVER_CAPS_NET/SERVER/RATE/QUOTA 按失败类型封顶换渠道次数(429/配额类瞬时失败时间预算形同虚设) - 预聚合:新增 usage_channel_hourlies(schema v10),记账事务内同步 upsert, 长窗口渠道统计走桶不再扫明细,spent_last_30d 改扫 usage_daily,v10 一次性回填幂等 - 守护:internal/arch_test.go 用 go/parser 强制分层依赖(fail-closed)
287 lines
8.8 KiB
Go
287 lines
8.8 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"
|
|
"github.com/shopspring/decimal"
|
|
"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
|
|
}
|
|
// 最后一个启用的管理员不可被降级/禁用:否则管理面被锁死,
|
|
// 且 reset-admin-password CLI 只在 admin 角色里找目标,救不回来。
|
|
if req.Role != nil || req.Status != nil {
|
|
var target store.User
|
|
if err := h.a.DB.First(&target, id).Error; err != nil {
|
|
resp.Fail(c, http.StatusNotFound, "user not found")
|
|
return
|
|
}
|
|
if target.Role == store.RoleAdmin && target.Status == store.UserStatusActive {
|
|
newRole, newStatus := target.Role, target.Status
|
|
if req.Role != nil {
|
|
newRole = *req.Role
|
|
}
|
|
if req.Status != nil {
|
|
newStatus = *req.Status
|
|
}
|
|
if newRole != store.RoleAdmin || newStatus != store.UserStatusActive {
|
|
var admins int64
|
|
h.a.DB.Model(&store.User{}).
|
|
Where("role = ? AND status = ? AND id != ?", store.RoleAdmin, store.UserStatusActive, id).
|
|
Count(&admins)
|
|
if admins == 0 {
|
|
resp.Fail(c, http.StatusBadRequest, "cannot demote or disable the last active admin")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// 模型限制(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 decimal.Decimal `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.IsZero() {
|
|
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
|
|
}
|
|
// SQL 侧原子加减:SQLite 驱动不支持行锁,Go 侧读-改-写会与记账扣费互相覆盖
|
|
if err := tx.Model(&store.User{}).Where("id = ?", id).Update("balance", gorm.Expr("balance + ?", req.Amount)).Error; err != nil {
|
|
return err
|
|
}
|
|
// ref_id 有单列唯一索引,秒级时间戳同一秒第二次调整必撞;纳秒粒度避免
|
|
ref := "admin:" + strconv.FormatUint(u.ID, 10) + ":" + strconv.FormatInt(time.Now().UnixNano(), 10)
|
|
_ = admin.ID // 流水里不冗余管理员 ID;需要时再加
|
|
return tx.Create(&store.BalanceLog{
|
|
UserID: u.ID,
|
|
Change: req.Amount,
|
|
BalanceAfter: u.Balance.Add(req.Amount),
|
|
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})
|
|
}
|
|
|
|
// InvalidateCatalogOnWrite 管理端写操作成功后清空网关的模型/渠道目录缓存。
|
|
// 缓存 TTL 只有 10s,但「改完渠道立刻生效」是管理员的合理预期;
|
|
// 用中间件统一处理,避免每个写 handler 都要记得调一次。
|
|
func (h *Handler) InvalidateCatalogOnWrite(c *gin.Context) {
|
|
c.Next()
|
|
switch c.Request.Method {
|
|
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
|
if h.gw != nil && c.Writer.Status() < 400 {
|
|
h.gw.InvalidateCatalog()
|
|
h.gw.InvalidateAuth() // 密钥白名单/用户状态/余额可能刚被改
|
|
}
|
|
}
|
|
}
|
|
|
|
// InvalidateAuthOnWrite 用户侧写操作(新建/改/删密钥)成功后清空网关鉴权缓存,
|
|
// 让被吊销的密钥立刻失效,而不是等 TTL 到期。
|
|
func (h *Handler) InvalidateAuthOnWrite(c *gin.Context) {
|
|
c.Next()
|
|
switch c.Request.Method {
|
|
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
|
if h.gw != nil && c.Writer.Status() < 400 {
|
|
h.gw.InvalidateAuth()
|
|
}
|
|
}
|
|
}
|