feat: 初始化 ChatGPT Team 管理后端项目

- 添加用户认证模块 (JWT + 密码管理)
- 添加 ChatGPT 账户管理功能
- 添加卡密管理功能 (创建、批量生成、查询)
- 添加邀请功能
- 配置数据库迁移和路由系统
This commit is contained in:
sar
2026-01-13 14:42:56 +08:00
commit 42c423bd32
29 changed files with 2969 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
package middleware
import (
"context"
"net/http"
"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]
// 解析 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)
})
}