This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/middleware/csrf.go
Victor_Jay 7bc2dbd970 refactor: 拆分 middleware/router 为单一职责文件,新增站点设置管理页面
middleware:
- 拆分 auth.go → auth.go + auth_token.go + auth_parser.go + auth_admin.go
- 拆分 csrf.go → csrf.go + csrf_token.go
- 拆分 ratelimit.go → ratelimit.go + ratelimit_core.go + ratelimit_cleanup.go
- 修复 import 未使用/缺失问题

router:
- 拆分 router.go → admin.go + api.go + frontend.go + deps_core.go + deps_extra.go

feat(admin): 站点设置管理页面
- 新增 SSR 页面 /admin/site-settings(仅 Owner)
- 审核开关 Toggle 即时保存
- 通用设置展示
- 侧边栏新增站点设置入口
- 注册 UpdateBoolSetting/GetBoolSetting API 路由
2026-05-27 15:03:04 +08:00

57 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"
"metazone.cc/metalab/internal/config"
"github.com/gin-gonic/gin"
)
const (
csrfCookieName = "mlb_csrf"
csrfHeaderName = "X-CSRF-Token"
csrfMetaName = "csrf_token"
)
// CSRF 中间件Double Submit Cookie 模式
func CSRF(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodGet ||
c.Request.Method == http.MethodHead ||
c.Request.Method == http.MethodOptions {
c.Next()
return
}
cookieToken, err := c.Cookie(csrfCookieName)
if err != nil || cookieToken == "" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败",
})
return
}
headerToken := c.GetHeader(csrfHeaderName)
if headerToken == "" {
headerToken = c.PostForm(csrfMetaName)
}
if headerToken == "" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败:缺少令牌",
})
return
}
if !constantTimeEq(cookieToken, headerToken) {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败",
})
return
}
c.Set(csrfMetaName, cookieToken)
c.Next()
}
}