Procházet zdrojové kódy

自动建立表-toekn

qdy před 1 měsícem
rodič
revize
5a71e61667
6 změnil soubory, kde provedl 167 přidání a 9 odebrání
  1. 44
    9
      config/loader.go
  2. 1
    0
      go.mod
  3. 2
    0
      go.sum
  4. 2
    0
      sdk/opencode/opencode_api_client.gen.go
  5. 111
    0
      util/jwt_util.go
  6. 7
    0
      webx/router/router_service.go

+ 44
- 9
config/loader.go Zobrazit soubor

67
 	return output
67
 	return output
68
 }
68
 }
69
 
69
 
70
-// findConfigFile 查找配置文件(内部函数保持不变)
70
+// findConfigFile 查找配置文件
71
 func findConfigFile() (string, error) {
71
 func findConfigFile() (string, error) {
72
 	exePath, _ := os.Executable()
72
 	exePath, _ := os.Executable()
73
 	exeDir := filepath.Dir(exePath)
73
 	exeDir := filepath.Dir(exePath)
74
 
74
 
75
+	// 获取当前工作目录
76
+	currentDir, err := os.Getwd()
77
+	if err != nil {
78
+		currentDir = "."
79
+	}
80
+
81
+	appName := filepath.Base(currentDir)
82
+	// 构建可能的配置文件路径
75
 	possiblePaths := []string{
83
 	possiblePaths := []string{
84
+
85
+		// 1. 当前目录的 appName.yaml
86
+		filepath.Join(currentDir, appName+".yaml"),
87
+
88
+		// 2. 当前目录的上级目录的 appName.yaml
89
+		filepath.Join(filepath.Dir(currentDir), appName+".yaml"),
90
+
91
+		// 3. 可执行文件所在目录的 appName.yaml
92
+		filepath.Join(exeDir, appName+".yaml"),
93
+
94
+		// 4. 可执行文件所在目录的上级目录的 appName.yaml
95
+		filepath.Join(filepath.Dir(exeDir), appName+".yaml"),
96
+
97
+		// 5. 原始逻辑中的 db.yaml 路径
76
 		filepath.Join(exeDir, "db.yaml"),
98
 		filepath.Join(exeDir, "db.yaml"),
77
 		filepath.Join(exeDir, "config", "db.yaml"),
99
 		filepath.Join(exeDir, "config", "db.yaml"),
78
 		"db.yaml",
100
 		"db.yaml",
79
 		"config/db.yaml",
101
 		"config/db.yaml",
102
+
103
+		// 6. 环境变量指定的路径
80
 		os.Getenv("DB_CONFIG_PATH"),
104
 		os.Getenv("DB_CONFIG_PATH"),
81
 	}
105
 	}
82
 
106
 
84
 		if path == "" {
108
 		if path == "" {
85
 			continue
109
 			continue
86
 		}
110
 		}
87
-		if _, err := os.Stat(path); err == nil {
88
-			log.Printf("✅ Using config file: %s\n", path)
89
-			return path, nil
111
+		log.Printf("find config file: %s", path)
112
+		// 清理路径
113
+		cleanPath := filepath.Clean(path)
114
+		if _, err := os.Stat(cleanPath); err == nil {
115
+			log.Printf("✅ Using config file: %s\n", cleanPath)
116
+			return cleanPath, nil
90
 		}
117
 		}
91
 	}
118
 	}
92
 
119
 
93
 	return "", fmt.Errorf(`no configuration file found
120
 	return "", fmt.Errorf(`no configuration file found
94
 
121
 
95
 Searched locations:
122
 Searched locations:
96
-1. %s
97
-2. %s
98
-3. ./db.yaml
99
-4. ./config/db.yaml
100
-5. DB_CONFIG_PATH环境变量指定的路径
123
+1. %s (当前目录)
124
+2. %s (上级目录)
125
+3. %s (可执行文件目录)
126
+4. %s (可执行文件上级目录)
127
+5. %s
128
+6. %s
129
+7. ./db.yaml
130
+8. ./config/db.yaml
131
+9. DB_CONFIG_PATH环境变量指定的路径
101
 
132
 
102
 请确保配置文件存在,或通过环境变量指定:
133
 请确保配置文件存在,或通过环境变量指定:
103
 export DB_CONFIG_PATH=/your/config/path/db.yaml
134
 export DB_CONFIG_PATH=/your/config/path/db.yaml
104
 set DB_CONFIG_PATH=C:\your\config\path\db.yaml (Windows)`,
135
 set DB_CONFIG_PATH=C:\your\config\path\db.yaml (Windows)`,
136
+		filepath.Join(currentDir, appName+".yaml"),
137
+		filepath.Join(filepath.Dir(currentDir), appName+".yaml"),
138
+		filepath.Join(exeDir, appName+".yaml"),
139
+		filepath.Join(filepath.Dir(exeDir), appName+".yaml"),
105
 		filepath.Join(exeDir, "db.yaml"),
140
 		filepath.Join(exeDir, "db.yaml"),
106
 		filepath.Join(exeDir, "config", "db.yaml"))
141
 		filepath.Join(exeDir, "config", "db.yaml"))
107
 }
142
 }

+ 1
- 0
go.mod Zobrazit soubor

44
 
44
 
45
 require (
45
 require (
46
 	github.com/elastic/go-elasticsearch/v8 v8.19.0
46
 	github.com/elastic/go-elasticsearch/v8 v8.19.0
47
+	github.com/golang-jwt/jwt/v5 v5.3.0
47
 	github.com/iancoleman/strcase v0.3.0
48
 	github.com/iancoleman/strcase v0.3.0
48
 	github.com/miekg/dns v1.1.68 // indirect
49
 	github.com/miekg/dns v1.1.68 // indirect
49
 	github.com/mitchellh/go-homedir v1.1.0 // indirect
50
 	github.com/mitchellh/go-homedir v1.1.0 // indirect

+ 2
- 0
go.sum Zobrazit soubor

24
 github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
24
 github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
25
 github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
25
 github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
26
 github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
26
 github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
27
+github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
28
+github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
27
 github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
29
 github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
28
 github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo=
30
 github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo=
29
 github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
31
 github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=

+ 2
- 0
sdk/opencode/opencode_api_client.gen.go Zobrazit soubor

13
 	"net/url"
13
 	"net/url"
14
 	"strings"
14
 	"strings"
15
 
15
 
16
+	"github.com/oapi-codegen/runtime"
17
+)
16
 
18
 
17
 // RequestEditorFn  is the function signature for the RequestEditor callback function
19
 // RequestEditorFn  is the function signature for the RequestEditor callback function
18
 type RequestEditorFn func(ctx context.Context, req *http.Request) error
20
 type RequestEditorFn func(ctx context.Context, req *http.Request) error

+ 111
- 0
util/jwt_util.go Zobrazit soubor

1
+package util
2
+
3
+import (
4
+	"fmt"
5
+	"time"
6
+
7
+	"github.com/golang-jwt/jwt/v5"
8
+)
9
+
10
+// Claims 结构定义
11
+type Claims struct {
12
+	UserID    string                 `json:"user_id"`
13
+	Username  string                 `json:"username"`
14
+	TenantID  string                 `json:"tenant_id"`
15
+	ProjectID string                 `json:"project_id"`
16
+	Extra     map[string]interface{} `json:"extra,omitempty"`
17
+	jwt.RegisteredClaims
18
+}
19
+
20
+// CreateToken 创建Token
21
+// claims: Claims对象
22
+// expiresHours: 过期小时数(0表示默认7天)
23
+// secretKey: 密钥
24
+func CreateToken(claims *Claims, expiresHours int, secretKey string) (string, error) {
25
+	return createTokenInternal(claims, 0, expiresHours, secretKey)
26
+}
27
+
28
+// CreateTokenDays 创建Token(按天)
29
+// claims: Claims对象
30
+// expiresDays: 过期天数(优先使用)
31
+// secretKey: 密钥
32
+func CreateTokenDays(claims *Claims, expiresDays int, secretKey string) (string, error) {
33
+	return createTokenInternal(claims, expiresDays, 0, secretKey)
34
+}
35
+
36
+// 内部实现
37
+func createTokenInternal(claims *Claims, expiresDays, expiresHours int, secretKey string) (string, error) {
38
+	if secretKey == "" {
39
+		return "", fmt.Errorf("secret key is required")
40
+	}
41
+	if claims == nil {
42
+		return "", fmt.Errorf("claims cannot be nil")
43
+	}
44
+
45
+	// 计算过期时间
46
+	var expiresDuration time.Duration
47
+	if expiresDays > 0 {
48
+		expiresDuration = time.Duration(expiresDays) * 24 * time.Hour
49
+	} else if expiresHours > 0 {
50
+		expiresDuration = time.Duration(expiresHours) * time.Hour
51
+	} else {
52
+		// 默认7天
53
+		expiresDuration = 7 * 24 * time.Hour
54
+	}
55
+
56
+	// 设置时间字段(内部处理)
57
+	now := time.Now()
58
+	claims.RegisteredClaims = jwt.RegisteredClaims{
59
+		ExpiresAt: jwt.NewNumericDate(now.Add(expiresDuration)),
60
+		IssuedAt:  jwt.NewNumericDate(now),
61
+		NotBefore: jwt.NewNumericDate(now),
62
+		Issuer:    "jwt-app",
63
+		Subject:   claims.UserID,
64
+	}
65
+
66
+	// 生成Token
67
+	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
68
+	return token.SignedString([]byte(secretKey))
69
+}
70
+
71
+// ParseToken 解析Token
72
+// tokenString: Token字符串
73
+// secretKey: 密钥
74
+func ParseToken(tokenString, secretKey string) (*Claims, error) {
75
+	if secretKey == "" {
76
+		return nil, fmt.Errorf("secret key is required")
77
+	}
78
+
79
+	claims := &Claims{}
80
+	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
81
+		return []byte(secretKey), nil
82
+	})
83
+
84
+	if err != nil {
85
+		return nil, fmt.Errorf("parse token failed: %w", err)
86
+	}
87
+
88
+	if !token.Valid {
89
+		return nil, fmt.Errorf("invalid token")
90
+	}
91
+
92
+	return claims, nil
93
+}
94
+
95
+// ValidateToken 验证Token是否有效
96
+func ValidateToken(tokenString, secretKey string) bool {
97
+	_, err := ParseToken(tokenString, secretKey)
98
+	return err == nil
99
+}
100
+
101
+// RefreshToken 刷新Token
102
+func RefreshToken(tokenString string, expiresHours int, secretKey string) (string, error) {
103
+	// 解析原Token
104
+	claims, err := ParseToken(tokenString, secretKey)
105
+	if err != nil {
106
+		return "", err
107
+	}
108
+
109
+	// 重新创建Token
110
+	return CreateToken(claims, expiresHours, secretKey)
111
+}

+ 7
- 0
webx/router/router_service.go Zobrazit soubor

96
 	description string
96
 	description string
97
 }
97
 }
98
 
98
 
99
+// WrapMiddleware 通用包装函数
100
+func WrapMiddleware[T any](middleware func(http.Handler, T) http.Handler, dep T) func(http.Handler) http.Handler {
101
+	return func(next http.Handler) http.Handler {
102
+		return middleware(next, dep)
103
+	}
104
+}
105
+
99
 // Use 添加路由级中间件
106
 // Use 添加路由级中间件
100
 func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
107
 func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
101
 	rb.middlewares = append(rb.middlewares, middleware...)
108
 	rb.middlewares = append(rb.middlewares, middleware...)

Loading…
Zrušit
Uložit