68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func RateLimit(
|
|
limiter *services.RateLimiter,
|
|
cfg services.RateLimitConfig,
|
|
keyFn func(c *gin.Context) string,
|
|
) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
key := keyFn(c)
|
|
|
|
allowed, remaining, _ := limiter.Allow(c.Request.Context(), key, cfg)
|
|
|
|
c.Header("X-RateLimit-Limit", itoa(cfg.Max))
|
|
c.Header("X-RateLimit-Remaining", itoa(remaining))
|
|
|
|
if !allowed {
|
|
c.JSON(http.StatusTooManyRequests, models.ErrTooManyRequests)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func LoginKeyFn(c *gin.Context) string {
|
|
var body struct {
|
|
Email string `json:"email"`
|
|
}
|
|
|
|
_ = c.ShouldBindBodyWithJSON(&body)
|
|
if body.Email != "" {
|
|
return "login:" + c.ClientIP() + ":" + body.Email
|
|
}
|
|
return "login:" + c.ClientIP()
|
|
}
|
|
|
|
func IPKeyFn(prefix string) func(c *gin.Context) string {
|
|
return func(c *gin.Context) string {
|
|
return prefix + ":" + c.ClientIP()
|
|
}
|
|
}
|
|
|
|
func itoa(n int) string {
|
|
if n < 0 {
|
|
return "0"
|
|
}
|
|
|
|
buf := make([]byte, 0, 10)
|
|
if n == 0 {
|
|
return "0"
|
|
}
|
|
|
|
for n > 0 {
|
|
buf = append([]byte{byte('0' + n%10)}, buf...)
|
|
n /= 10
|
|
}
|
|
return string(buf)
|
|
}
|