Inicial
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/limiter"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type redisStorage struct {
|
||||
client *goredis.Client
|
||||
}
|
||||
|
||||
func NewRedisStorage(client *goredis.Client) *redisStorage {
|
||||
return &redisStorage{client: client}
|
||||
}
|
||||
|
||||
func (s *redisStorage) Get(key string) ([]byte, error) {
|
||||
val, err := s.client.Get(context.Background(), key).Bytes()
|
||||
if err == goredis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
return val, err
|
||||
}
|
||||
|
||||
func (s *redisStorage) Set(key string, val []byte, exp time.Duration) error {
|
||||
return s.client.Set(context.Background(), key, val, exp).Err()
|
||||
}
|
||||
|
||||
func (s *redisStorage) Delete(key string) error {
|
||||
return s.client.Del(context.Background(), key).Err()
|
||||
}
|
||||
|
||||
func (s *redisStorage) Reset() error {
|
||||
return s.client.FlushDB(context.Background()).Err()
|
||||
}
|
||||
|
||||
func (s *redisStorage) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func RateLimiter(storage *redisStorage) fiber.Handler {
|
||||
return limiter.New(limiter.Config{
|
||||
Max: 10,
|
||||
Expiration: 1 * time.Minute,
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
return "ratelimit:auth:" + c.IP()
|
||||
},
|
||||
Storage: storage,
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
return fiber.NewError(429, "muitas tentativas, tente novamente em 1 minuto")
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user