feat: add request limiter

This commit is contained in:
Urko 2023-07-09 21:58:26 +02:00
parent 37ac1ac797
commit b13e9dcf8d
1 changed files with 8 additions and 9 deletions

View File

@ -1,14 +1,15 @@
package api
import (
"fmt"
"log"
"time"
"gitea.urkob.com/urko/prosody-password/internal/api/handler"
"gitea.urkob.com/urko/prosody-password/internal/services/fail2ban"
"gitea.urkob.com/urko/prosody-password/internal/services/prosody"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/limiter"
"github.com/gofiber/template/handlebars/v2"
)
@ -34,7 +35,12 @@ func (s *RestServer) Start(apiPort, views string) error {
Views: engine,
})
// Or extend your config for customization
s.app.Use(limiter.New(limiter.Config{
Max: 5,
Expiration: 1 * time.Hour,
LimiterMiddleware: limiter.SlidingWindow{},
}))
s.app.Use(cors.New(cors.Config{
AllowMethods: "POST,OPTIONS",
AllowOrigins: "*",
@ -46,13 +52,6 @@ func (s *RestServer) Start(apiPort, views string) error {
prosodyHdl := handler.NewProsodyHandler(s.prosodyService, s.fail2banSrv)
s.app.Post("/changePassword", func(c *fiber.Ctx) error {
log.Println("c.IPs()", c.IPs())
log.Println("c.IP", c.IP())
for _, ip := range c.IPs() {
if !s.fail2banSrv.CanChangePassword(ip) {
return handler.RenderError(c, fmt.Errorf("id is empty"), "Too many tries, blocked for 1h")
}
}
return prosodyHdl.Post(c)
})