refactor: complete backend rewrite for multi-protocol proxy

Major rewrite of the Go backend to support:
- Three API format imports: openai, anthropic, compatible
- Three protocol conversions: Chat Completions, Responses, Messages
- Hub-and-spoke architecture with Chat as intermediate format

Deleted:
- opencat.go (old entry)
- store/, team/, pkg/team/, pkg/store/ (old data layer)
- internal/model/, internal/consts/ (old types)
- internal/service/team/, internal/controller/team/ (old handlers)
- llm/ (removed LLM client library, pure proxy mode)
- dist/, assets/ (old build artifacts)

Added:
- internal/store/ — 9 GORM models + multi-DB support
- internal/pkg/ — crypto (AES-GCM), apikey, jwt, ratelimit, resp, tokenizer
- internal/channel/ — channel selection, weighted LB, health checks
- internal/proxy/convert/ — 6 protocol conversion functions + SSE streaming
- internal/proxy/ — gateway with request dispatch and upstream selection
- internal/usage/ — async usage recorder with batch writes
- internal/api/ — management API (auth, users, keys, channels, models)
- Makefile for build/test/deploy

Fixed API to match frontend expectations:
- Login response wraps token in { data: { token } }
- GET /api/profile route added
- Profile response wraps user in { code, data }
- Role returned as number (10=admin, 1=user)
This commit is contained in:
Sakurasan
2026-08-30 11:49:31 +08:00
parent aa0d87f132
commit ef3025dd80
127 changed files with 4623 additions and 10500 deletions
+38 -40
View File
@@ -1,55 +1,53 @@
package middleware
import (
"fmt"
"net/http"
"opencatd-open/internal/auth"
"opencatd-open/internal/consts"
"opencatd-open/internal/dto"
"opencatd-open/internal/model"
"opencatd-open/pkg/store"
"opencatd-open/internal/store"
"opencatd-open/internal/pkg/jwt"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func Auth(c *gin.Context) {
authToken := c.GetHeader("Authorization")
if authToken == "" {
dto.Fail(c, http.StatusUnauthorized, "未提供认证信息")
return
func Auth(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
authToken := c.GetHeader("Authorization")
if authToken == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"error": "未提供认证信息",
})
return
}
if len(authToken) > 7 {
authToken = authToken[7:]
}
claim, err := jwt.ValidateToken(authToken, auth.GetSecretKey())
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"error": "无效的认证信息",
})
return
}
var user store.User
if err := db.First(&user, claim.UserID).Error; err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"error": "无效的认证信息",
})
return
}
c.Set("user", &user)
c.Set("user_id", claim.UserID)
c.Set("user_role", user.Role)
c.Next()
}
authToken = authToken[7:]
claim, err := auth.ValidateToken(authToken, consts.SecretKey)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"error": "无效的认证信息",
})
return
}
var user model.User
if err := store.GetDB().Model(&model.User{ID: int64(claim.UserID)}).First(&user).Error; err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"error": "无效的认证信息",
})
return
}
c.Set("user", &user)
c.Set("user_id", claim.UserID)
c.Set("user_role", user.Role)
c.Next()
}
func CheckRole(role consts.UserRole) func(c *gin.Context) {
fmt.Println("CheckRoleMiddleware")
func CheckRole(role string) gin.HandlerFunc {
return func(c *gin.Context) {
userRole := c.GetInt("user_role") // 操作者
fmt.Println("userRole", userRole)
// if userRole < int(role) {
// dto.Fail(c, http.StatusForbidden, "permission denied")
// return
// }
c.Next()
}
}
+67
View File
@@ -0,0 +1,67 @@
package middleware
import (
"net/http"
"opencatd-open/internal/store"
"strings"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func AuthLLM(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
authToken := c.GetHeader("Authorization")
if authToken == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": map[string]interface{}{
"message": "未提供认证信息",
"type": "invalid_request_error",
},
})
return
}
// Extract API key from Bearer token
if len(authToken) > 7 {
authToken = authToken[7:]
}
// Find API key by prefix
var apiKey store.APIKey
if err := db.Where("key_prefix = ? AND status = ?", authToken[:8], store.KeyStatusActive).First(&apiKey).Error; err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": map[string]interface{}{
"message": "无效的API密钥",
"type": "invalid_request_error",
},
})
return
}
// Verify full key hash
keyHash := store.HashAPIKey(authToken)
if apiKey.KeyHash != keyHash {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": map[string]interface{}{
"message": "无效的API密钥",
"type": "invalid_request_error",
},
})
return
}
c.Set("api_key", &apiKey)
c.Set("user_id", apiKey.UserID)
c.Next()
}
}
// extractAPIKey extracts the API key from the Authorization header
func extractAPIKey(c *gin.Context) string {
auth := c.GetHeader("Authorization")
if strings.HasPrefix(auth, "Bearer ") {
return auth[7:]
}
return auth
}
-105
View File
@@ -1,105 +0,0 @@
package middleware
import (
"net/http"
"opencatd-open/internal/dto"
"opencatd-open/internal/model"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func AuthTeam(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
auth_token := c.GetHeader("Authorization")
if len(auth_token) < 7 || auth_token[:7] != "Bearer " {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
auth_token = auth_token[7:]
token := model.Token{}
if err := db.Preload("Users").First(&token, "token = ?", auth_token).Error; err != nil {
dto.WrapErrorAsOpenAI(c, http.StatusUnauthorized, "invalid_api_key")
c.Abort()
return
}
if token.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
if !*token.User.Active || !*token.Active {
dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "User or API key is not active")
c.Abort()
return
}
if token.Name != "default" {
dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "Only default api key accessible")
c.Abort()
return
}
c.Set("user", token.User)
c.Set("authed", true)
// 可以在这里对 token 进行验证并检查权限
c.Next()
}
}
func AuthLLM(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
auth_token := c.GetHeader("Authorization")
if len(auth_token) < 7 || auth_token[:7] != "Bearer " {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
auth_token = auth_token[7:]
token := model.Token{}
if err := db.Preload("User").Where("key = ?", auth_token).First(&token).Error; err != nil {
dto.WrapErrorAsOpenAI(c, http.StatusUnauthorized, "invalid_api_key")
c.Abort()
return
}
if token.User == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
if !*token.User.Active || !*token.Active {
dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "User or API key is not active")
c.Abort()
return
}
if !*token.User.UnlimitedQuota && *token.User.Quota <= 0 {
dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "quota_exceeded")
c.Abort()
return
}
if !*token.UnlimitedQuota && *token.Quota <= 0 {
dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "quota_exceeded")
c.Abort()
return
}
c.Set("user", token.User)
c.Set("user_id", token.User.ID)
c.Set("token_id", token.ID)
c.Set("authed", true)
// 可以在这里对 token 进行验证并检查权限
c.Next()
}
}