Files
mengyaping/mengyaping-backend/middleware/admin.go
2026-05-16 19:03:32 +08:00

44 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"mengyaping-backend/models"
"mengyaping-backend/storage"
)
// AdminAuth 校验管理员令牌:环境变量 ADMIN_TOKEN 优先,否则使用 MySQL monitor_kv 中的 admin_token请求头 X-Admin-Token 或 Authorization: Bearer
func AdminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
expected := storage.GetStorage().EffectiveAdminToken()
if expected == "" {
c.AbortWithStatusJSON(http.StatusServiceUnavailable, models.APIResponse{
Code: 503,
Message: "未配置管理员令牌:请在数据库 monitor_kv 写入 admin_token或设置环境变量 ADMIN_TOKEN",
})
return
}
got := strings.TrimSpace(c.GetHeader("X-Admin-Token"))
if got == "" {
auth := c.GetHeader("Authorization")
const prefix = "Bearer "
if len(auth) >= len(prefix) && strings.EqualFold(auth[:len(prefix)], prefix) {
got = strings.TrimSpace(auth[len(prefix):])
}
}
if got == "" || got != expected {
c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIResponse{
Code: 401,
Message: "无效的管理员令牌",
})
return
}
c.Next()
}
}