You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.2 KiB
90 lines
2.2 KiB
// Code scaffolded by goctl. Safe to edit.
|
|
// goctl 1.9.2
|
|
|
|
package ai
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type AiApiKeyListLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 获取我的API Key列表
|
|
func NewAiApiKeyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AiApiKeyListLogic {
|
|
return &AiApiKeyListLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *AiApiKeyListLogic) AiApiKeyList(req *types.AIApiKeyListRequest) (resp *types.AIApiKeyListResponse, err error) {
|
|
userId, _ := l.ctx.Value("userId").(int64)
|
|
|
|
// Query keys belonging to current user or system keys (userId=0)
|
|
var keys []model.AIApiKey
|
|
var total int64
|
|
query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.AIApiKey{}).Where("user_id = ? OR user_id = 0", userId)
|
|
if err = query.Count(&total).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
offset := (req.Page - 1) * req.PageSize
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
if err = query.Order("created_at DESC").Offset(int(offset)).Limit(int(req.PageSize)).Find(&keys).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Build provider name cache to avoid repeated queries
|
|
providerCache := make(map[int64]string)
|
|
list := make([]types.AIApiKeyInfo, 0, len(keys))
|
|
for _, key := range keys {
|
|
providerName := ""
|
|
if name, ok := providerCache[key.ProviderId]; ok {
|
|
providerName = name
|
|
} else {
|
|
provider, provErr := model.AIProviderFindOne(l.ctx, l.svcCtx.DB, key.ProviderId)
|
|
if provErr == nil {
|
|
providerName = provider.DisplayName
|
|
}
|
|
providerCache[key.ProviderId] = providerName
|
|
}
|
|
|
|
list = append(list, types.AIApiKeyInfo{
|
|
Id: key.Id,
|
|
ProviderId: key.ProviderId,
|
|
ProviderName: providerName,
|
|
UserId: key.UserId,
|
|
KeyPreview: maskKey(key.KeyValue),
|
|
IsActive: key.IsActive,
|
|
Remark: key.Remark,
|
|
CreatedAt: key.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
})
|
|
}
|
|
|
|
resp = &types.AIApiKeyListResponse{
|
|
List: list,
|
|
Total: total,
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
func maskKey(key string) string {
|
|
if len(key) <= 10 {
|
|
return "sk-***"
|
|
}
|
|
return key[:6] + "..." + key[len(key)-4:]
|
|
}
|
|
|