用 Go (Gin + GORM + SQLite) 重写整个后端: - 单二进制部署,不依赖 Python/pip/SDK - net/http 原生客户端,无 Cloudflare TLS 指纹问题 - 多阶段 Dockerfile:Node 构建前端 + Go 构建后端 + Alpine 运行 - 内存占用从 ~95MB 降至 ~3MB - 完整保留所有 API 路由、JWT 认证、API Key 权限、审计日志
85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"airwallex-admin/models"
|
|
)
|
|
|
|
func APIKeyAuth() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
apiKey := c.GetHeader("X-API-Key")
|
|
if apiKey == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Missing API key"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
var token models.ApiToken
|
|
result := models.DB.Where("token = ?", apiKey).First(&token)
|
|
if result.Error != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"detail": "Invalid API key"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if !token.IsActive {
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "API key is inactive"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if token.ExpiresAt != nil && token.ExpiresAt.Before(time.Now()) {
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "API key has expired"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Update last_used_at
|
|
now := time.Now()
|
|
models.DB.Model(&token).Update("last_used_at", now)
|
|
|
|
c.Set("api_token", token)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func CheckPermission(requiredPerm string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
val, exists := c.Get("api_token")
|
|
if !exists {
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "No API token in context"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
token, ok := val.(models.ApiToken)
|
|
if !ok {
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "Invalid API token in context"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
var permissions []string
|
|
if err := json.Unmarshal([]byte(token.Permissions), &permissions); err != nil {
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "Invalid permissions format"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
for _, perm := range permissions {
|
|
if perm == "*" || perm == requiredPerm {
|
|
c.Next()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusForbidden, gin.H{"detail": "Insufficient permissions"})
|
|
c.Abort()
|
|
}
|
|
}
|