From b803ebf8307c34215a9a5d0a9313009eba88174c Mon Sep 17 00:00:00 2001 From: "suguo.yao" Date: Mon, 27 Nov 2023 21:50:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8D=E9=80=9A=E5=95=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- ddns.http | 9 +++++++-- gin/auth-filter.go | 34 +++++++++++++++++++++++++++++++--- 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index c03e07b..8c6b9d4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ ddns *.exe logs/ -go.sum \ No newline at end of file +go.sum +.vscode/ \ No newline at end of file diff --git a/ddns.http b/ddns.http index 891b8c2..1b6dc02 100644 --- a/ddns.http +++ b/ddns.http @@ -1,8 +1,13 @@ @url=http://127.0.0.1:8080/ddns +@ts=1701014400 -POST {{url}}/register/581243B8B72744FBAE4EFC472492DDAF HTTP/1.1 +### +POST {{url}}/register/581243B8B72744FBAE4EFC472492DDAF?timestamp={{ts}}&key=0540 HTTP/1.1 { "ipv6":"240e:391:1a4d:91c0:951c:da68:892d:d904", "level":"ipv6" -} \ No newline at end of file +} + + + diff --git a/gin/auth-filter.go b/gin/auth-filter.go index 62e9af3..d9ce00f 100644 --- a/gin/auth-filter.go +++ b/gin/auth-filter.go @@ -1,20 +1,48 @@ package gin import ( + "fmt" + "strconv" + "time" + "github.com/gin-gonic/gin" ) // 从redis中认证用户 func AuthUser() gin.HandlerFunc { return func(c *gin.Context) { - token := c.Query("key") + key := c.Query("key") ts := c.Query("timestamp") + t, err := strconv.ParseInt(ts, 10, 32) + if err != nil { + c.AbortWithStatus(401) + return + } + currentTime := time.Now().Unix() - if token != ts { - c.Abort() + t = 1701014400 + currentTime = 1701014400 + + if currentTime-t > 5 || t-currentTime > 3 { + c.AbortWithStatus(401) + return + } + result := currentTime % 2260 + if extractDigits(result, 2, 5) != key { + c.AbortWithStatus(401) return } c.Next() } } + +// extractDigits 提取数字 n 中的 start 到 end 位数字 +func extractDigits(n, start, end int64) string { + strN := fmt.Sprintf("%d", n) + // 在前面填充零,直到达到提取的最大位数 + for len(strN) < int(end) { + strN = "0" + strN + } + return strN[start-1 : end] +}