From 0dda9bdd8c71ad1f628f8685078dcf1c53543792 Mon Sep 17 00:00:00 2001 From: Erfan Mahdavi <53367157+erfanwd@users.noreply.github.com> Date: Wed, 18 Dec 2024 23:29:39 +0330 Subject: [PATCH] fix: RemoteAddr returns ip with port that changes each time so we should get ip without port (#8) --- src/api/middleware/otp_limiter.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/api/middleware/otp_limiter.go b/src/api/middleware/otp_limiter.go index 0d2d3fb..c1fa1cb 100644 --- a/src/api/middleware/otp_limiter.go +++ b/src/api/middleware/otp_limiter.go @@ -2,6 +2,7 @@ package middleware import ( "errors" + "net" "net/http" "time" @@ -15,7 +16,7 @@ import ( func OtpLimiter(cfg *config.Config) gin.HandlerFunc { var limiter = limiter.NewIPRateLimiter(rate.Every(cfg.Otp.Limiter*time.Second), 1) return func(c *gin.Context) { - limiter := limiter.GetLimiter(c.Request.RemoteAddr) + limiter := limiter.GetLimiter(getIP(c.Request.RemoteAddr)) if !limiter.Allow() { c.AbortWithStatusJSON(http.StatusTooManyRequests, helper.GenerateBaseResponseWithError(nil, false, helper.OtpLimiterError, errors.New("not allowed"))) c.Abort() @@ -24,3 +25,11 @@ func OtpLimiter(cfg *config.Config) gin.HandlerFunc { } } } + +func getIP(remoteAddr string) string { + ip, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + return remoteAddr + } + return ip +}