4b35736f73
P0 (5): crypto/rand session ID, TTS fallback可达性, goroutine defer recover, adminAuth前缀修正 P1 (5): 普通用户密码验证, context传递, priority clamp, 超时重试, 自主思考速率限制 P2 (4): Briefing AI降级, 前端消息类型渲染, Docker Compose补全, PWA 192图标 P3 (5): goroutine错误处理, .gitignore完善, reminder created_at, voice Dockerfile, Go版本更新
58 lines
1.3 KiB
Go
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, strings.HasPrefix(userID, "admin_"))
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// GetUserID 从上下文获取用户ID
|
|
func GetUserID(c *gin.Context) string {
|
|
userID, _ := c.Get(UserIDKey)
|
|
if userID == nil {
|
|
return ""
|
|
}
|
|
return userID.(string)
|
|
}
|