- 卡密列表展示与分页功能 - 单个/批量创建卡密 - 卡密删除与批量删除 - 卡密导出功能 (file-saver) - 启用/禁用状态切换 - 状态判断 (有效/已使用/已失效) - Toast 通知系统 (vue-sonner) - 登录页面错误提示优化 - 后端登录错误消息中文化
66 lines
1.7 KiB
Go
66 lines
1.7 KiB
Go
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)
|
|
})
|
|
}
|