49 lines
904 B
Go
49 lines
904 B
Go
package gin
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 从redis中认证用户
|
|
func AuthUser() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
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()
|
|
|
|
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]
|
|
}
|