Skip to content

Commit 148e8be

Browse files
committed
feat: 支持gemini认证key
1 parent 96d3fc7 commit 148e8be

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

internal/middleware/middleware.go

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -137,31 +137,19 @@ func Auth(config types.AuthConfig) gin.HandlerFunc {
137137
return
138138
}
139139

140-
// Get authorization header
141-
authHeader := c.GetHeader("Authorization")
142-
if authHeader == "" {
140+
// Extract key from multiple sources
141+
key := extractKey(c)
142+
if key == "" {
143143
c.JSON(401, gin.H{
144-
"error": "Authorization header required",
144+
"error": "Authorization required",
145145
"code": errors.ErrAuthMissing,
146146
})
147147
c.Abort()
148148
return
149149
}
150150

151-
// Check Bearer token format
152-
const bearerPrefix = "Bearer "
153-
if !strings.HasPrefix(authHeader, bearerPrefix) {
154-
c.JSON(401, gin.H{
155-
"error": "Invalid authorization format, expected 'Bearer <token>'",
156-
"code": errors.ErrAuthInvalid,
157-
})
158-
c.Abort()
159-
return
160-
}
161-
162-
// Extract and validate token
163-
token := authHeader[len(bearerPrefix):]
164-
if token != config.Key {
151+
// Validate key
152+
if key != config.Key {
165153
c.JSON(401, gin.H{
166154
"error": "Invalid authentication token",
167155
"code": errors.ErrAuthInvalid,
@@ -252,3 +240,28 @@ func isMonitoringEndpoint(path string) bool {
252240
}
253241
return false
254242
}
243+
244+
// extractKey extracts the API key from the request, checking the Authorization header,
245+
// the X-Goog-Api-Key header, and the "key" query parameter.
246+
func extractKey(c *gin.Context) string {
247+
// 1. Check Authorization header
248+
authHeader := c.GetHeader("Authorization")
249+
if authHeader != "" {
250+
const bearerPrefix = "Bearer "
251+
if strings.HasPrefix(authHeader, bearerPrefix) {
252+
return authHeader[len(bearerPrefix):]
253+
}
254+
}
255+
256+
// 2. Check X-Goog-Api-Key header
257+
if key := c.GetHeader("X-Goog-Api-Key"); key != "" {
258+
return key
259+
}
260+
261+
// 3. Check "key" query parameter
262+
if key := c.Query("key"); key != "" {
263+
return key
264+
}
265+
266+
return ""
267+
}

0 commit comments

Comments
 (0)