nezha/cmd/dashboard/controller/waf/waf.go

58 lines
1.3 KiB
Go
Raw Normal View History

2024-11-22 10:57:25 -05:00
package waf
import (
_ "embed"
"net/http"
"strings"
"github.com/gin-gonic/gin"
2024-11-22 11:58:15 -05:00
2024-11-28 06:38:54 -05:00
"github.com/nezhahq/nezha/model"
"github.com/nezhahq/nezha/pkg/utils"
"github.com/nezhahq/nezha/service/singleton"
2024-11-22 10:57:25 -05:00
)
//go:embed waf.html
var errorPageTemplate string
func RealIp(c *gin.Context) {
if singleton.Conf.RealIPHeader == "" {
c.Next()
return
}
if singleton.Conf.RealIPHeader == model.ConfigUsePeerIP {
c.Set(model.CtxKeyRealIPStr, c.RemoteIP())
c.Next()
return
}
vals := c.Request.Header.Get(singleton.Conf.RealIPHeader)
if vals == "" {
c.AbortWithStatusJSON(http.StatusOK, model.CommonResponse[any]{Success: false, Error: "real ip header not found"})
return
}
2024-11-22 21:21:01 -05:00
ip, err := utils.GetIPFromHeader(vals)
2024-11-22 10:57:25 -05:00
if err != nil {
c.AbortWithStatusJSON(http.StatusOK, model.CommonResponse[any]{Success: false, Error: err.Error()})
return
}
2024-11-22 21:21:01 -05:00
c.Set(model.CtxKeyRealIPStr, ip)
2024-11-22 10:57:25 -05:00
c.Next()
}
func Waf(c *gin.Context) {
2024-11-22 21:21:01 -05:00
if err := model.CheckIP(singleton.DB, c.GetString(model.CtxKeyRealIPStr)); err != nil {
2024-11-22 11:58:15 -05:00
ShowBlockPage(c, err)
2024-11-22 10:57:25 -05:00
return
}
c.Next()
}
func ShowBlockPage(c *gin.Context, err error) {
c.Writer.WriteHeader(http.StatusForbidden)
c.Header("Content-Type", "text/html; charset=utf-8")
c.Writer.WriteString(strings.Replace(errorPageTemplate, "{error}", err.Error(), 1))
c.Abort()
}