Add api key logic to handle rate limit in api (#918)
This commit is contained in:
parent
1c075e3745
commit
fba3adef65
|
@ -120,7 +120,9 @@ func (r *Repository) GetAddressOverview(ctx context.Context, params *GetAddressO
|
|||
zap.String("_id", documents[i].ID),
|
||||
)
|
||||
}
|
||||
vaas = append(vaas, &documents[i].Vaas[0])
|
||||
if len(documents[i].Vaas) > 1 {
|
||||
vaas = append(vaas, &documents[i].Vaas[0])
|
||||
}
|
||||
}
|
||||
return &AddressOverview{Vaas: vaas}, nil
|
||||
}
|
||||
|
|
|
@ -64,6 +64,8 @@ type AppConfig struct {
|
|||
Max int
|
||||
// Prefix for redis keys
|
||||
Prefix string
|
||||
//Api Tokens
|
||||
Tokens string
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -124,3 +126,7 @@ func Get() (*AppConfig, error) {
|
|||
err := viper.Unmarshal(&cfg)
|
||||
return &cfg, err
|
||||
}
|
||||
|
||||
func (c *AppConfig) GetApiTokens() []string {
|
||||
return strings.Split(c.RateLimit.Tokens, ",")
|
||||
}
|
||||
|
|
16
api/main.go
16
api/main.go
|
@ -297,6 +297,14 @@ func NewRateLimiter(ctx context.Context, cfg *config.AppConfig, logger *zap.Logg
|
|||
cfg.RateLimit.Prefix = "rate-limiter:"
|
||||
}
|
||||
|
||||
enableApiTokens := len(cfg.GetApiTokens()) > 0
|
||||
enableByApiToken := make(map[string]bool)
|
||||
if enableApiTokens {
|
||||
for _, token := range cfg.GetApiTokens() {
|
||||
enableByApiToken[token] = true
|
||||
}
|
||||
}
|
||||
|
||||
// initialize rate limiter
|
||||
store, err := frs.New(
|
||||
frs.Config{URL: cfg.Cache.URL, Prefix: cfg.RateLimit.Prefix})
|
||||
|
@ -317,7 +325,13 @@ func NewRateLimiter(ctx context.Context, cfg *config.AppConfig, logger *zap.Logg
|
|||
|
||||
router := limiter.New(limiter.Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
|
||||
if enableApiTokens {
|
||||
apiKey := c.Get("X-API-KEY")
|
||||
if apiKey != "" {
|
||||
_, exists := enableByApiToken[apiKey]
|
||||
return exists
|
||||
}
|
||||
}
|
||||
ip := utils.GetRealIp(c)
|
||||
return utils.IsPrivateIPAsString(ip)
|
||||
},
|
||||
|
|
|
@ -5,7 +5,7 @@ go 1.19
|
|||
require (
|
||||
github.com/ansrivas/fiberprometheus/v2 v2.6.0
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/gagliardetto/solana-go v1.8.2
|
||||
github.com/gagliardetto/solana-go v1.8.4
|
||||
github.com/go-resty/resty/v2 v2.7.0
|
||||
github.com/gofiber/fiber/v2 v2.47.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
|
|
Loading…
Reference in New Issue