From 9275b28827a4d6ed559685457286f2d25a9ecc6b Mon Sep 17 00:00:00 2001 From: Vegard Berg Date: Wed, 13 Sep 2023 21:02:11 +0200 Subject: [PATCH] Add usage limit based on IP --- controllers/new.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/controllers/new.go b/controllers/new.go index ccdd1c9..7a77790 100644 --- a/controllers/new.go +++ b/controllers/new.go @@ -31,6 +31,12 @@ func PostNewHandler(c echo.Context) error { lang := c.FormValue("lang") ip := c.RealIP() + if tooMany, period := ipHasTooManyUses(ip); tooMany { + return utils.RenderErrorToast(c, + fmt.Sprintf("This IP address has uploaded too many files in the %s", period), + ) + } + if (file == nil || err != nil) && text == "" { return utils.RenderErrorToast(c, "file or text must be provided") } @@ -98,3 +104,39 @@ func getTextFromFile(fileHeader *multipart.FileHeader) (text string, err error) text = string(b) return } + +func ipHasTooManyUses(ip string) (tooMany bool, period string) { + file := new(models.File) + var dayCount int64 + global.DB.Model(file). + Where("ip = ? AND created_date >= DATETIME('now', '-1 day')", ip). + Count(&dayCount) + + var threeDayCount int64 + global.DB.Model(file). + Where("ip = ? AND created_date >= DATETIME('now', '-3 days')", ip). + Count(&threeDayCount) + + var weekCount int64 + global.DB.Model(file). + Where("ip = ? AND created_date >= DATETIME('now', '-7 days')", ip). + Count(&weekCount) + + var monthCount int64 + global.DB.Model(file). + Where("ip = ? AND created_date >= DATETIME('now', '-1 month')", ip). + Count(&monthCount) + + if dayCount > 20 { + return true, "last day" + } else if threeDayCount > 50 { + return true, "last three days" + } else if weekCount > 85 { + return true, "last week" + } else if monthCount > 300 { + return true, "last month" + } + + return false, "" + +}