2026-03-31 18:58:05 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/1Panel-dev/1Panel/core/app/dto"
|
|
|
|
|
"github.com/1Panel-dev/1Panel/core/constant"
|
|
|
|
|
"github.com/1Panel-dev/1Panel/core/global"
|
2026-04-01 19:22:08 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/core/i18n"
|
2026-03-31 18:58:05 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func CSRFTokenGuard() gin.HandlerFunc {
|
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
|
if !requiresCSRFTokenCheck(c) {
|
|
|
|
|
c.Next()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
token := strings.TrimSpace(c.GetHeader(constant.CSRFHeaderName))
|
|
|
|
|
if !global.SESSION.CheckCSRFToken(c, token) {
|
|
|
|
|
c.AbortWithStatusJSON(http.StatusForbidden, dto.Response{
|
|
|
|
|
Code: http.StatusForbidden,
|
2026-04-01 19:22:08 +08:00
|
|
|
Message: i18n.GetMsgWithMap("ErrNotLogin", map[string]interface{}{"detail": "CSRF token invalid"}),
|
2026-03-31 18:58:05 +08:00
|
|
|
Data: nil,
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func requiresCSRFTokenCheck(c *gin.Context) bool {
|
2026-06-17 15:31:51 +08:00
|
|
|
if c.GetBool("LOCAL_REQUEST") {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2026-03-31 18:58:05 +08:00
|
|
|
unsafeMethod := c.Request.Method != http.MethodGet &&
|
|
|
|
|
c.Request.Method != http.MethodHead &&
|
|
|
|
|
c.Request.Method != http.MethodOptions &&
|
|
|
|
|
c.Request.Method != http.MethodTrace
|
|
|
|
|
if !unsafeMethod {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
if !strings.HasPrefix(c.Request.URL.Path, "/api/v2/") {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
switch c.Request.URL.Path {
|
|
|
|
|
case "/api/v2/core/auth/login",
|
|
|
|
|
"/api/v2/core/auth/mfalogin",
|
|
|
|
|
"/api/v2/core/auth/passkey/begin",
|
2026-08-03 13:43:01 +08:00
|
|
|
"/api/v2/core/auth/passkey/finish",
|
|
|
|
|
"/api/v2/core/auth/oidc/begin",
|
|
|
|
|
"/api/v2/core/auth/oidc/finish":
|
|
|
|
|
return false
|
|
|
|
|
case "/api/v2/core/auth/saml2/begin",
|
|
|
|
|
"/api/v2/core/auth/saml2/acs",
|
|
|
|
|
"/api/v2/core/auth/saml2/finish",
|
|
|
|
|
"/api/v2/core/auth/saml2/logout":
|
2026-03-31 18:58:05 +08:00
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
if c.GetBool("API_AUTH") {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
sessionID, err := c.Cookie(constant.SessionName)
|
|
|
|
|
return err == nil && sessionID != ""
|
|
|
|
|
}
|