Skip to content

Commit

Permalink
Limit added
Browse files Browse the repository at this point in the history
  • Loading branch information
Zenon-provalidator committed Jul 5, 2023
1 parent b352e2d commit aa95eb8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 17 deletions.
1 change: 1 addition & 0 deletions models/DB.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ type ApiUsage struct {
Ip string `json:"ip"`
Method string `json:"method"`
Date string `json:"date"`
Cnt int `json:"cnt"`
}
6 changes: 6 additions & 0 deletions models/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,9 @@ func WriteLog(sub string, token string, ip string, method string) {
input := ApiUsage{Sub: sub, Token: token, Ip: ip, Method: method, Date: date}
DB.Create(&input)
}

func Count(sub string) int {
apiUsage := ApiUsage{}
DB.Raw("SELECT count(1) AS cnt FROM ( SELECT * FROM nodereal.api_usages WHERE date BETWEEN DATE_ADD(NOW(),INTERVAL -1 MONTH ) AND NOW() ) AS a WHERE a.sub= ?", sub).Scan(&apiUsage)
return apiUsage.Cnt
}
21 changes: 8 additions & 13 deletions models/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ func TestDB(t *testing.T) {
// DB
ConnectDatabase()
log.Logger.Info.Println(DbStr)
Read()
Write()
Read()
Update()
Read()
Delete()
Read()
// Read()
// Write()
// Read()
// Update()
// Read()
// Delete()
// Read()
log.Logger.Info.Println("cnt", Count("9900cd1f-9cf1-44fb-857e-b189eb0fe249"))

}

Expand All @@ -54,12 +55,6 @@ func Read() {
log.Logger.Info.Println(apiUsage)
}

func Check(token string) {
var apiUsage = ApiUsage{}
// DB.Where("token = ?", token).First(apiUsage)
DB.Exec("").First(apiUsage)
}

func Write() {
log.Logger.Info.Println("Write test")
input := ApiUsage{Token: "test", Method: "/asddf", Date: "2012-02-20 12:11:11"}
Expand Down
13 changes: 9 additions & 4 deletions routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,16 @@ func AuthorizationMiddleware(c *gin.Context) {
return
}
// Usage check from DB
// 1. Read usage data ( * find by tokenString)
// 1. Read usage data ( sub )
requestsCnt := models.Count(claims.Sub)

// 2. Usage process

// 3. Write usage data
if requestsCnt >= 100000 {
log.Logger.Error.Println("Exceeded the limit.", "sub:", claims.Sub, "(", requestsCnt, ")")
c.JSON(http.StatusUnauthorized, gin.H{"status": http.StatusUnauthorized, "error": "You've already exceeded the limit. (100,000 Requests)"})
c.Abort()
return
}
// 2. Write usage data Log
models.WriteLog(claims.Sub, tokenString, c.ClientIP(), c.Request.URL.Path)

c.Next()
Expand Down

0 comments on commit aa95eb8

Please sign in to comment.