Browse Source

增加工作ID和tokend的对照表

liwei 1 week ago
parent
commit
dc4117dec7

+ 5 - 2
internal/logic/chat/chat_completions_logic.go

@@ -38,6 +38,7 @@ func (l *ChatCompletionsLogic) ChatCompletions(req *types.CompApiReq) (resp *typ
 		apiKeyObj *ent.ApiKey
 		ok        bool
 	)
+	workToken := compapi.GetWorkTokenByID(req.EventType, req.WorkId)
 	apiKeyObj, ok = contextkey.AuthTokenInfoKey.GetValue(l.ctx)
 	if !ok {
 		return nil, errors.New("content get token err")
@@ -48,12 +49,14 @@ func (l *ChatCompletionsLogic) ChatCompletions(req *types.CompApiReq) (resp *typ
 		fmt.Printf("Title:'%s'\n", apiKeyObj.Title)
 		fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
 		fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
+		fmt.Printf("workToken:'%s' because %s/%s\n", workToken, req.EventType, req.WorkId)
 		fmt.Println("=========================================")
 	*/
-	if len(apiKeyObj.OpenaiBase) == 0 || len(apiKeyObj.OpenaiKey) == 0 {
+
+	if len(apiKeyObj.OpenaiBase) == 0 || len(workToken) == 0 {
 		return nil, errors.New("not auth info")
 	}
-	return l.workForFastgpt(req, apiKeyObj.OpenaiKey, apiKeyObj.OpenaiBase)
+	return l.workForFastgpt(req, workToken, apiKeyObj.OpenaiBase)
 }
 
 func (l *ChatCompletionsLogic) workForFastgpt(req *types.CompApiReq, apiKey string, apiBase string) (resp *types.CompOpenApiResp, err error) {

+ 41 - 23
internal/middleware/openauthority_middleware.go

@@ -2,11 +2,15 @@ package middleware
 
 import (
 	"context"
+	"encoding/json"
+	"fmt"
 	"net/http"
+	"reflect"
 
 	"wechat-api/ent"
 	"wechat-api/ent/apikey"
 	"wechat-api/ent/predicate"
+	"wechat-api/internal/utils/compapi"
 	"wechat-api/internal/utils/contextkey"
 
 	"wechat-api/internal/config"
@@ -36,39 +40,62 @@ func NewOpenAuthorityMiddleware(db *ent.Client, rds redis.UniversalClient, c con
 	}
 }
 
-func (m *OpenAuthorityMiddleware) checkTokenUserInfo(ctx context.Context, loginToken string) (*ent.ApiKey, error) {
+func (m *OpenAuthorityMiddleware) checkTokenUserInfo(ctx context.Context, authToken string) (*ent.ApiKey, int, error) {
 	var (
 		rc  int
 		err error
 		val *ent.ApiKey
 	)
+	val, rc, err = m.getTokenUserInfoByDb(ctx, authToken)
+	return val, rc, err
+
 	/*
 		r, e = m.getTokenUserInfoByRds(ctx, loginToken)
 		fmt.Println("redis:", "code-", r, "err-", e)
 	*/
-	val, rc, err = m.getTokenUserInfoByDb(ctx, loginToken)
-	_ = rc
-	if err != nil {
-		return nil, err
-	}
-	return val, nil
+	/*
+		//首先从redis取数据
+		_, rc, err = m.getTokenUserInfoByRds(ctx, authToken)
+		fmt.Printf("++++++++++++++++++++++++get authinfo from rds out:%d/err:%s\n", rc, err)
+		if rc <= 0 || err != nil { //无法获得后再从数据库获得
+			rc = 0
+			err = nil
+			val, rc, err = m.getTokenUserInfoByDb(ctx, authToken)
+			fmt.Println("----------------------After m.getTokenUserInfoByDb:", val)
+			err = m.saveTokenUserInfoToRds(ctx, authToken, val)
+			fmt.Println("------------save saveTokenUserInfoToRd err:", err)
+		}
+
+		_ = rc
+		if err != nil {
+			return nil, 0, err
+		}
+		return val, 0, nil
+	*/
 }
 
-/*
-func (m *OpenAuthorityMiddleware) getTokenUserInfoByRds(ctx context.Context, loginToken string) (code int, err error) {
+func (m *OpenAuthorityMiddleware) saveTokenUserInfoToRds(ctx context.Context, authToken string, saveInfo *ent.ApiKey) error {
+	if bs, err := json.Marshal(saveInfo); err == nil {
+		return err
+	} else {
+		rc, err := m.Rds.HSet(ctx, compapi.APIAuthInfoKey, authToken, string(bs)).Result()
+		fmt.Printf("#~~~~~~~~~~~~~~~++~~~~~~~~~~~~~HSet Val:%s get Result:%d/%s\n", string(bs), rc, err)
+		return err
+	}
+}
+func (m *OpenAuthorityMiddleware) getTokenUserInfoByRds(ctx context.Context, authToken string) (*ent.ApiKey, int, error) {
 
 	rcode := -1
-	val, err := m.Rds.HGet(ctx, "api_key", loginToken).Result()
+	val, err := m.Rds.HGet(ctx, compapi.APIAuthInfoKey, authToken).Result()
 	if err == redis.Nil {
 		rcode = 0
 	} else if err == nil {
 		rcode = 1
 	}
-	fmt.Printf("From Redis By Key:'%s' Get '%s'(%v)\n", loginToken, val, val)
+	fmt.Printf("#####################From Redis By Key:'%s' Get '%s'(%s/%T)\n", authToken, val, reflect.TypeOf(val), val)
 	fmt.Println(val)
-	return rcode, err
+	return nil, rcode, err
 }
-*/
 
 func (m *OpenAuthorityMiddleware) getTokenUserInfoByDb(ctx context.Context, loginToken string) (*ent.ApiKey, int, error) {
 	rcode := -1
@@ -92,7 +119,7 @@ func (m *OpenAuthorityMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc
 			httpx.Error(w, errorx.NewApiError(http.StatusForbidden, "无法获取token"))
 			return
 		}
-		apiKeyObj, err := m.checkTokenUserInfo(ctx, authToken)
+		apiKeyObj, _, err := m.checkTokenUserInfo(ctx, authToken)
 		if err != nil {
 			httpx.Error(w, errorx.NewApiError(http.StatusForbidden, "无法获取合适的授权信息"))
 			return
@@ -106,16 +133,7 @@ func (m *OpenAuthorityMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc
 			fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
 			fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
 			fmt.Println("=========================================")
-			claims, err := jwtutils.ParseJwtToken(m.Config.Auth.AccessSecret, authToken)
-			fmt.Println("claims")
-			fmt.Printf("%+v\n", claims)
-			if err != nil {
-				logx.Errorw("check user auth error", logx.Field("detail", err.Error()))
-				httpx.Error(w, errorx.NewApiError(http.StatusInternalServerError, err.Error()))
-				return
-			}
 		*/
-
 		newReq := r.WithContext(ctx)
 		// Passthrough to next handler if need
 		next(w, newReq)

+ 16 - 0
internal/utils/compapi/config.go

@@ -7,4 +7,20 @@ import (
 const (
 	ChatModelDeepSeekV3 openai.ChatModel = "deepseek-chat"
 	ChatModelDeepSeekR1 openai.ChatModel = "deepseek-reasoner"
+
+	APIAuthInfoKey string = "COMPAPI_AUTHINFO"
 )
+
+var fastgptWorkIdMap = map[string]string{
+	"default":              "fastgpt-jcDATa9aH4vtUsjDpCU773BxmLU50IxKUX9nUT0mCTLQkEoo1hPxPEdNQeOEWGTn",
+	"OPTIMIZE_CALL_SCRIPT": "fastgpt-bcQ9cWKd6y9a2LfizweeWEnukkQi1Oq46yoiRg9yDNLm8NPTWXsyFwcB",
+}
+
+// 获取workToken
+func GetWorkTokenByID(eventType string, workId string) string {
+	val, exist := fastgptWorkIdMap[workId]
+	if !exist {
+		val = fastgptWorkIdMap["default"]
+	}
+	return val
+}