From 3f059e0babf6762a945d6ae3dd9cabf085aba8f0 Mon Sep 17 00:00:00 2001 From: ttk Date: Thu, 4 Jul 2024 15:17:21 +0800 Subject: [PATCH] feat: multi pattern for auth by ip --- conf/confTemplate.yaml | 5 +++-- main.go | 1 + middleware/auth.go | 22 +++++++++++++++++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/conf/confTemplate.yaml b/conf/confTemplate.yaml index 68c5f28..39d28fa 100644 --- a/conf/confTemplate.yaml +++ b/conf/confTemplate.yaml @@ -3,8 +3,9 @@ app: port: 8888 auths: - # - type: ip - # pattern: 192.168.*.* + - type: ip + pattern: + - 192.168.*.*,127.0.0.1 # - type: token # token: your token diff --git a/main.go b/main.go index 1c3177e..1bd76f7 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,7 @@ func main() { gin.SetMode(gin.ReleaseMode) r := gin.Default() + r.SetTrustedProxies([]string{"0.0.0.0/0", "::/0"}) g1 := r.Group("/v1").Use(middleware.Auth(authConf), middleware.Error2Resp()) { g1.POST("/message", send.PushMessage) diff --git a/middleware/auth.go b/middleware/auth.go index 1dc8f9e..ec63a0d 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "fmt" "net/http" - "path/filepath" "sort" "strings" "time" @@ -44,8 +43,25 @@ var ( ) func authByIP(conf map[string]string, ctx *gin.Context) bool { - m, err := filepath.Match(conf["pattern"], ctx.ClientIP()) - return m && err == nil + ip := ctx.ClientIP() + ps := strings.Split(conf["pattern"], ",") + for _, p := range ps { + ss1 := strings.Split(p, ".") + ss2 := strings.Split(ip, ".") + if len(ss1) != len(ss2) { + continue + } + b := true + for i := 0; i < len(ss1) && b; i++ { + if ss1[i] != "*" && ss1[i] != ss2[i] { + b = false + } + } + if b { + return true + } + } + return false } func authByToken(conf map[string]string, ctx *gin.Context) bool {