Skip to content

Commit

Permalink
Merge pull request #16 from veops/dev
Browse files Browse the repository at this point in the history
feat: multi pattern for auth by ip
  • Loading branch information
ttktatakai authored Jul 4, 2024
2 parents 64d87e1 + 3f059e0 commit 9abd6e3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
5 changes: 3 additions & 2 deletions conf/confTemplate.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
22 changes: 19 additions & 3 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/base64"
"fmt"
"net/http"
"path/filepath"
"sort"
"strings"
"time"
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 9abd6e3

Please sign in to comment.