This repository has been archived on 2026-08-12. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Cyrene/backend/gateway/internal/middleware/auth.go
T
AskaEth 1fc2b41d36 fix: 将管理员 user_id 从动态 admin_{username} 改为固定 admin
根因:admin user_id 由 admin_ + req.Username 动态拼接,
当 .env 中 ADMIN_USERNAME 更改时,新登录会生成不同的 user_id,
导致旧会话成为孤儿且消息历史不可见。

修复方案 (Plan A):
- auth_handler.go: Login 时 userID 固定为 admin
- auth.go: IsAdminKey 从 HasPrefix(admin_) 改为 == admin
- chat_handler.go: 主对话管理员检查改为 userID == admin
- memory_handler.go: 3处 admin_ 前缀检查改为 == admin
- briefing_handler.go: 3处 admin_ 前缀检查改为 != admin
- sessionStore.ts: isAdminUser 从 startsWith 改为 ===
- MessageBubble.tsx: UserAvatar 管理员判断改为 ===
- main.go: 添加旧管理员用户清理逻辑 (ListUsers+DeleteUser)
- user_store.go: 新增 ListUsers 和 DeleteUser 函数
- ai-core/main.go: adminUserID 从 admin_admin 改为 admin
- memory-service/store.go: 默认 user_id 改为 admin
- memory-service/memory_service.go: 默认 UserID 改为 admin
- devtools/src/index.js: URL 参数 user_id=admin

验证: Go build 通过 (gateway/ai-core/memory-service),
tsc --noEmit 通过, vite build 通过
2026-05-20 22:13:21 +08:00

58 lines
1.3 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/yourname/cyrene-ai/gateway/internal/config"
)
// Auth 用户键值在context中的key
const UserIDKey = "user_id"
const IsAdminKey = "is_admin"
// JWTAuth JWT认证中间件
func JWTAuth(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
c.Abort()
return
}
// Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "认证格式错误"})
c.Abort()
return
}
tokenString := parts[1]
userID, err := cfg.ValidateToken(tokenString)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "认证令牌无效或已过期"})
c.Abort()
return
}
// 将userID注入上下文
c.Set(UserIDKey, userID)
// 设置管理员标记 (admin 用户 ID 为固定值 "admin")
c.Set(IsAdminKey, userID == "admin")
c.Next()
}
}
// GetUserID 从上下文获取用户ID
func GetUserID(c *gin.Context) string {
userID, _ := c.Get(UserIDKey)
if userID == nil {
return ""
}
return userID.(string)
}