优化 API 密钥管理与展示

- 每个商户限制最多 5 个 API 密钥,超限拒绝创建并提示
- API 密钥权限列改用中文标签展示,新增按用途命名提示
- 优化 API 密钥表格列宽,App Key 完整单行展示
- 补充密钥数量上限测试
This commit is contained in:
yml2213
2026-07-31 19:58:17 +08:00
parent eac025c92f
commit 8672ab2dca
3 changed files with 85 additions and 13 deletions
+10
View File
@@ -461,6 +461,9 @@ type CreateAPIClientInput struct {
ExpiresAt *time.Time
}
// MaxAPIClientsPerMerchant 每个商户最多可创建的 API 密钥数量,防止密钥滥用。
const MaxAPIClientsPerMerchant = 5
func (s *MerchantService) CreateAPIClient(merchantID uint, in CreateAPIClientInput, actorUserID uint) (*APICredential, error) {
in.Name = strings.TrimSpace(in.Name)
if in.Name == "" {
@@ -502,6 +505,13 @@ func (s *MerchantService) CreateAPIClient(merchantID uint, in CreateAPIClientInp
if err := tx.Where("id = ? AND status = ?", merchantID, model.MerchantStatusActive).First(&merchant).Error; err != nil {
return errors.New("商户不存在或已禁用")
}
var clientCount int64
if err := tx.Model(&model.APIClient{}).Where("merchant_id = ?", merchantID).Count(&clientCount).Error; err != nil {
return err
}
if clientCount >= MaxAPIClientsPerMerchant {
return fmt.Errorf("每个商户最多可创建 %d 个 API 密钥", MaxAPIClientsPerMerchant)
}
if err := tx.Create(client).Error; err != nil {
return err
}
+37
View File
@@ -0,0 +1,37 @@
package service
import (
"fmt"
"strings"
"testing"
"affiliate_dash/internal/model"
)
func TestCreateAPIClientEnforcesPerMerchantLimit(t *testing.T) {
db := newServiceTestDB(t)
codec, err := NewSecretCodec("test-master-key")
if err != nil {
t.Fatalf("codec: %v", err)
}
svc := NewMerchantService(db, codec, NewTenantService(db))
merchant := model.Merchant{Code: "merchant-api-limit", Name: "限数商户", Status: model.MerchantStatusActive}
if err := db.Create(&merchant).Error; err != nil {
t.Fatalf("create merchant: %v", err)
}
for i := 0; i < MaxAPIClientsPerMerchant; i++ {
if _, err := svc.CreateAPIClient(merchant.ID, CreateAPIClientInput{
Name: fmt.Sprintf("key-%d", i),
Scopes: "products:read",
}, 1); err != nil {
t.Fatalf("create client %d: %v", i, err)
}
}
_, err = svc.CreateAPIClient(merchant.ID, CreateAPIClientInput{
Name: "overflow",
Scopes: "products:read",
}, 1)
if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("最多可创建 %d 个", MaxAPIClientsPerMerchant)) {
t.Fatalf("expected per-merchant limit error, got %v", err)
}
}