- 添加全局 API Token 认证支持 (环境变量 API_TOKEN) - Team 页面添加直接邀请按钮 - Team 页面添加随机邀请按钮 - 修复已邀请用户列表字段名不匹配问题 - 修复数据库为空时错误显示 toast 的问题
81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"gpt-manager-go/internal/auth"
|
|
)
|
|
|
|
// 上下文键类型
|
|
type contextKey string
|
|
|
|
const UserContextKey contextKey = "user"
|
|
|
|
// AuthMiddleware JWT 认证中间件
|
|
func AuthMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
http.Error(w, `{"success":false,"message":"Authorization header required"}`, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// 检查 Bearer 前缀
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
http.Error(w, `{"success":false,"message":"Invalid authorization header format"}`, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
|
|
// 首先检查是否是 API Token
|
|
apiToken := os.Getenv("API_TOKEN")
|
|
if apiToken != "" && tokenString == apiToken {
|
|
// API Token 认证成功,创建虚拟管理员上下文
|
|
claims := &auth.Claims{
|
|
UserID: 0,
|
|
Username: "api_token",
|
|
IsSuperAdmin: true,
|
|
}
|
|
ctx := context.WithValue(r.Context(), UserContextKey, claims)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
return
|
|
}
|
|
|
|
// 解析 JWT Token
|
|
claims, err := auth.ParseToken(tokenString)
|
|
if err != nil {
|
|
http.Error(w, `{"success":false,"message":"Invalid or expired token"}`, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// 将用户信息存入上下文
|
|
ctx := context.WithValue(r.Context(), UserContextKey, claims)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// GetUserFromContext 从上下文获取用户信息
|
|
func GetUserFromContext(ctx context.Context) *auth.Claims {
|
|
if claims, ok := ctx.Value(UserContextKey).(*auth.Claims); ok {
|
|
return claims
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RequireSuperAdmin 要求超级管理员权限
|
|
func RequireSuperAdmin(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
claims := GetUserFromContext(r.Context())
|
|
if claims == nil || !claims.IsSuperAdmin {
|
|
http.Error(w, `{"success":false,"message":"Super admin required"}`, http.StatusForbidden)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|