mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-09-24 16:05:44 +08:00
Merge pull request #3869 from Birditch/feat/admin-user-role-and-token-ranking
feat(admin): 用户角色管理 + 用户 Token 排行
This commit is contained in:
@@ -675,6 +675,9 @@ func (h *DashboardHandler) GetUserBreakdown(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// sort_by 由 repo 层 allowlist 校验;非法值静默回退默认排序(actual_cost)。
|
||||
dim.SortBy = strings.TrimSpace(c.Query("sort_by"))
|
||||
|
||||
limit := 50
|
||||
if v := c.Query("limit"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
|
||||
|
||||
@@ -59,7 +59,21 @@ func TestGetUserBreakdown_GroupIDFilter(t *testing.T) {
|
||||
require.Equal(t, int64(42), repo.capturedDim.GroupID)
|
||||
require.Empty(t, repo.capturedDim.Model)
|
||||
require.Empty(t, repo.capturedDim.Endpoint)
|
||||
require.Equal(t, 50, repo.capturedLimit) // default limit
|
||||
require.Equal(t, 50, repo.capturedLimit) // default limit
|
||||
require.Empty(t, repo.capturedDim.SortBy) // no sort_by => empty (repo falls back to default)
|
||||
}
|
||||
|
||||
func TestGetUserBreakdown_SortBy(t *testing.T) {
|
||||
repo := &userBreakdownRepoCapture{}
|
||||
router := newUserBreakdownRouter(repo)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/admin/dashboard/user-breakdown?start_date=2026-03-01&end_date=2026-03-16&sort_by=total_tokens", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(t, "total_tokens", repo.capturedDim.SortBy)
|
||||
}
|
||||
|
||||
func TestGetUserBreakdown_ModelFilter(t *testing.T) {
|
||||
|
||||
@@ -53,6 +53,7 @@ type CreateUserRequest struct {
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Username string `json:"username"`
|
||||
Notes string `json:"notes"`
|
||||
Role string `json:"role" binding:"omitempty,oneof=admin user"`
|
||||
Balance *float64 `json:"balance"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
RPMLimit int `json:"rpm_limit"`
|
||||
@@ -66,6 +67,7 @@ type UpdateUserRequest struct {
|
||||
Password string `json:"password" binding:"omitempty,min=6"`
|
||||
Username *string `json:"username"`
|
||||
Notes *string `json:"notes"`
|
||||
Role string `json:"role" binding:"omitempty,oneof=admin user"`
|
||||
Balance *float64 `json:"balance"`
|
||||
Concurrency *int `json:"concurrency"`
|
||||
RPMLimit *int `json:"rpm_limit"`
|
||||
@@ -269,6 +271,7 @@ func (h *UserHandler) Create(c *gin.Context) {
|
||||
Password: req.Password,
|
||||
Username: req.Username,
|
||||
Notes: req.Notes,
|
||||
Role: req.Role,
|
||||
Balance: req.Balance,
|
||||
Concurrency: req.Concurrency,
|
||||
RPMLimit: req.RPMLimit,
|
||||
@@ -297,12 +300,20 @@ func (h *UserHandler) Update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 防锁死保护:管理员不能把自己降级为普通用户(单管理员场景下会失去后台访问权)。
|
||||
// 与既有"不能禁用/删除 admin"保护一致。降级其他管理员仍然允许。
|
||||
if req.Role == service.RoleUser && userID == getAdminIDFromContext(c) {
|
||||
response.BadRequest(c, "cannot demote yourself from admin")
|
||||
return
|
||||
}
|
||||
|
||||
// 使用指针类型直接传递,nil 表示未提供该字段
|
||||
user, err := h.adminService.UpdateUser(c.Request.Context(), userID, &service.UpdateUserInput{
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
Username: req.Username,
|
||||
Notes: req.Notes,
|
||||
Role: req.Role,
|
||||
Balance: req.Balance,
|
||||
Concurrency: req.Concurrency,
|
||||
RPMLimit: req.RPMLimit,
|
||||
|
||||
@@ -164,13 +164,16 @@ type UserSpendingRankingResponse struct {
|
||||
|
||||
// UserBreakdownItem represents per-user usage breakdown within a dimension (group, model, endpoint).
|
||||
type UserBreakdownItem struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Requests int64 `json:"requests"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost"` // 账号成本
|
||||
UserID int64 `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Requests int64 `json:"requests"`
|
||||
InputTokens int64 `json:"input_tokens"` // 输入 token 累计
|
||||
OutputTokens int64 `json:"output_tokens"` // 输出 token 累计
|
||||
CacheTokens int64 `json:"cache_tokens"` // 缓存创建 + 读取 token 累计
|
||||
TotalTokens int64 `json:"total_tokens"` // 输入+输出+缓存 token 累计
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost"` // 账号成本
|
||||
}
|
||||
|
||||
// UserBreakdownDimension specifies the dimension to filter for user breakdown.
|
||||
@@ -187,6 +190,8 @@ type UserBreakdownDimension struct {
|
||||
RequestType *int16 // filter by request_type (non-nil to enable)
|
||||
Stream *bool // filter by stream flag (non-nil to enable)
|
||||
BillingType *int8 // filter by billing_type (non-nil to enable)
|
||||
// SortBy 指定排序列(空 = 默认按 actual_cost)。合法值由 repo 层 allowlist 校验。
|
||||
SortBy string
|
||||
}
|
||||
|
||||
// APIKeyUsageTrendPoint represents API key usage trend data point
|
||||
|
||||
@@ -603,6 +603,9 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
COALESCE(ul.user_id, 0) as user_id,
|
||||
COALESCE(u.email, '') as email,
|
||||
COUNT(*) as requests,
|
||||
COALESCE(SUM(ul.input_tokens), 0) as input_tokens,
|
||||
COALESCE(SUM(ul.output_tokens), 0) as output_tokens,
|
||||
COALESCE(SUM(ul.cache_creation_tokens + ul.cache_read_tokens), 0) as cache_tokens,
|
||||
COALESCE(SUM(ul.input_tokens + ul.output_tokens + ul.cache_creation_tokens + ul.cache_read_tokens), 0) as total_tokens,
|
||||
COALESCE(SUM(ul.total_cost), 0) as cost,
|
||||
COALESCE(SUM(ul.actual_cost), 0) as actual_cost,
|
||||
@@ -651,7 +654,13 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
args = append(args, *dim.BillingType)
|
||||
}
|
||||
|
||||
query += " GROUP BY ul.user_id, u.email ORDER BY actual_cost DESC"
|
||||
// ORDER BY 列来自固定 allowlist(非用户原样字符串),避免 SQL 注入。
|
||||
orderBy := "actual_cost"
|
||||
switch dim.SortBy {
|
||||
case "total_tokens", "input_tokens", "output_tokens", "cache_tokens", "requests", "cost", "actual_cost":
|
||||
orderBy = dim.SortBy
|
||||
}
|
||||
query += " GROUP BY ul.user_id, u.email ORDER BY " + orderBy + " DESC"
|
||||
if limit > 0 {
|
||||
query += fmt.Sprintf(" LIMIT %d", limit)
|
||||
}
|
||||
@@ -674,6 +683,9 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
&row.UserID,
|
||||
&row.Email,
|
||||
&row.Requests,
|
||||
&row.InputTokens,
|
||||
&row.OutputTokens,
|
||||
&row.CacheTokens,
|
||||
&row.TotalTokens,
|
||||
&row.Cost,
|
||||
&row.ActualCost,
|
||||
|
||||
@@ -125,6 +125,7 @@ type CreateUserInput struct {
|
||||
Password string
|
||||
Username string
|
||||
Notes string
|
||||
Role string // 空字符串表示使用默认角色(user);合法值 admin/user
|
||||
Balance *float64
|
||||
Concurrency int
|
||||
RPMLimit int
|
||||
@@ -136,6 +137,7 @@ type UpdateUserInput struct {
|
||||
Password string
|
||||
Username *string
|
||||
Notes *string
|
||||
Role string // 空字符串表示"未提供"(不修改);合法值 admin/user
|
||||
Balance *float64 // 使用指针区分"未提供"和"设置为0"
|
||||
Concurrency *int // 使用指针区分"未提供"和"设置为0"
|
||||
RPMLimit *int // 使用指针区分"未提供"和"设置为0"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAdminService_CreateUser_WithAdminRole(t *testing.T) {
|
||||
repo := &userRepoStub{nextID: 30}
|
||||
svc := &adminServiceImpl{userRepo: repo}
|
||||
|
||||
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
|
||||
Email: "admin@test.com",
|
||||
Password: "strong-pass",
|
||||
Role: RoleAdmin,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RoleAdmin, user.Role)
|
||||
}
|
||||
|
||||
func TestAdminService_CreateUser_DefaultsToUserRole(t *testing.T) {
|
||||
repo := &userRepoStub{nextID: 31}
|
||||
svc := &adminServiceImpl{userRepo: repo}
|
||||
|
||||
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
|
||||
Email: "plain@test.com",
|
||||
Password: "strong-pass",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RoleUser, user.Role)
|
||||
}
|
||||
|
||||
func TestAdminService_CreateUser_InvalidRoleRejected(t *testing.T) {
|
||||
repo := &userRepoStub{nextID: 32}
|
||||
svc := &adminServiceImpl{userRepo: repo}
|
||||
|
||||
_, err := svc.CreateUser(context.Background(), &CreateUserInput{
|
||||
Email: "bad@test.com",
|
||||
Password: "strong-pass",
|
||||
Role: "superuser",
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Empty(t, repo.created, "非法角色不应写入用户")
|
||||
}
|
||||
|
||||
func TestAdminService_UpdateUser_PromoteToAdmin(t *testing.T) {
|
||||
base := &userRepoStub{user: &User{ID: 42, Email: "u@example.com", Role: RoleUser}}
|
||||
repo := &rpmUserRepoStub{userRepoStub: base}
|
||||
invalidator := &authCacheInvalidatorStub{}
|
||||
svc := &adminServiceImpl{
|
||||
userRepo: repo,
|
||||
redeemCodeRepo: &redeemRepoStub{},
|
||||
authCacheInvalidator: invalidator,
|
||||
}
|
||||
|
||||
updated, err := svc.UpdateUser(context.Background(), 42, &UpdateUserInput{Role: RoleAdmin})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RoleAdmin, updated.Role)
|
||||
require.Equal(t, []int64{42}, invalidator.userIDs, "角色变更应失效认证缓存")
|
||||
}
|
||||
|
||||
func TestAdminService_UpdateUser_RoleOmittedKeepsExisting(t *testing.T) {
|
||||
base := &userRepoStub{user: &User{ID: 42, Email: "u@example.com", Role: RoleAdmin}}
|
||||
repo := &rpmUserRepoStub{userRepoStub: base}
|
||||
svc := &adminServiceImpl{userRepo: repo, redeemCodeRepo: &redeemRepoStub{}}
|
||||
|
||||
newName := "renamed"
|
||||
updated, err := svc.UpdateUser(context.Background(), 42, &UpdateUserInput{Username: &newName})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RoleAdmin, updated.Role, "未提供 role 时不应改变现有角色")
|
||||
}
|
||||
|
||||
func TestAdminService_UpdateUser_InvalidRoleRejected(t *testing.T) {
|
||||
base := &userRepoStub{user: &User{ID: 42, Email: "u@example.com", Role: RoleUser}}
|
||||
repo := &rpmUserRepoStub{userRepoStub: base}
|
||||
svc := &adminServiceImpl{userRepo: repo, redeemCodeRepo: &redeemRepoStub{}}
|
||||
|
||||
_, err := svc.UpdateUser(context.Background(), 42, &UpdateUserInput{Role: "root"})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, repo.lastUpdated, "非法角色不应触发持久化")
|
||||
}
|
||||
@@ -105,6 +105,18 @@ func (s *adminServiceImpl) GetUserIncludeDeleted(ctx context.Context, id int64)
|
||||
return s.userRepo.GetByIDIncludeDeleted(ctx, id)
|
||||
}
|
||||
|
||||
// normalizeUserRole 校验并归一化角色输入。
|
||||
// 空字符串返回 fallback(未提供时的默认角色);非法值返回错误。
|
||||
func normalizeUserRole(role, fallback string) (string, error) {
|
||||
if role == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
if role != RoleAdmin && role != RoleUser {
|
||||
return "", fmt.Errorf("invalid role: %q (must be %s or %s)", role, RoleAdmin, RoleUser)
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) CreateUser(ctx context.Context, input *CreateUserInput) (*User, error) {
|
||||
balance := 0.0
|
||||
if input.Balance != nil {
|
||||
@@ -113,11 +125,17 @@ func (s *adminServiceImpl) CreateUser(ctx context.Context, input *CreateUserInpu
|
||||
balance = s.settingService.GetDefaultBalance(ctx)
|
||||
}
|
||||
|
||||
// 角色可由管理员在创建时指定(admin/user);未提供时默认 user。
|
||||
role, err := normalizeUserRole(input.Role, RoleUser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := &User{
|
||||
Email: input.Email,
|
||||
Username: input.Username,
|
||||
Notes: input.Notes,
|
||||
Role: RoleUser, // Always create as regular user, never admin
|
||||
Role: role,
|
||||
Balance: balance,
|
||||
Concurrency: input.Concurrency,
|
||||
RPMLimit: input.RPMLimit,
|
||||
@@ -197,6 +215,15 @@ func (s *adminServiceImpl) UpdateUser(ctx context.Context, id int64, input *Upda
|
||||
user.Status = input.Status
|
||||
}
|
||||
|
||||
// 角色变更(admin/user);空字符串表示不修改。
|
||||
if input.Role != "" {
|
||||
role, err := normalizeUserRole(input.Role, user.Role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.Role = role
|
||||
}
|
||||
|
||||
if input.Concurrency != nil {
|
||||
user.Concurrency = *input.Concurrency
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user