// Code scaffolded by goctl. Safe to edit. // goctl 1.9.2 package ai import ( "context" "fmt" "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 AiApiKeyUpdateLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } // 更新API Key func NewAiApiKeyUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AiApiKeyUpdateLogic { return &AiApiKeyUpdateLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *AiApiKeyUpdateLogic) AiApiKeyUpdate(req *types.AIApiKeyUpdateRequest) (resp *types.AIApiKeyInfo, err error) { userId, _ := l.ctx.Value("userId").(int64) // Find existing key existing, err := model.AIApiKeyFindOne(l.ctx, l.svcCtx.DB, req.Id) if err != nil { if err == model.ErrNotFound { return nil, fmt.Errorf("API Key不存在") } return nil, fmt.Errorf("查询API Key失败: %v", err) } // Verify ownership: must be the user's own key or a system key (userId=0) if existing.UserId != userId && existing.UserId != 0 { return nil, fmt.Errorf("无权更新此API Key") } // Update fields if req.KeyValue != "" { existing.KeyValue = req.KeyValue } existing.IsActive = req.IsActive existing.Remark = req.Remark if err = model.AIApiKeyUpdate(l.ctx, l.svcCtx.DB, existing); err != nil { return nil, fmt.Errorf("更新API Key失败: %v", err) } // Look up provider name providerName := "" provider, provErr := model.AIProviderFindOne(l.ctx, l.svcCtx.DB, existing.ProviderId) if provErr == nil { providerName = provider.DisplayName } resp = &types.AIApiKeyInfo{ Id: existing.Id, ProviderId: existing.ProviderId, ProviderName: providerName, UserId: existing.UserId, KeyPreview: maskKey(existing.KeyValue), IsActive: existing.IsActive, Remark: existing.Remark, CreatedAt: existing.CreatedAt.Format("2006-01-02 15:04:05"), } return resp, nil }