Rack-Attack: Array of IP addresses

故事扮演 提交于 2019-12-04 16:44:34

An efficient way to do this would be to use a Set, a container that's like an array but provides fast lookup on individual, unique elements.

So, rewritten with that in mind:

allowed = %w[ 127.0.0.1 1.2.3.4 ].to_set

Rack::Attack.blacklist('allow from localhost') do |req|
  !allowed.include?(req.ip)
end

In your original declaration:

a = "x", "y"

In this case a is assigned to the first thing in that list, "x", and the rest is ignored.

First off it would be nice if you were more explicit about creating an array and write

a = ["127.0.0.1", "1.2.3.4"]

but it's even better to use Set

allowed = Set.new['127.0.0.1', '1.2.3.4']

(also using single-quotes should save time as Ruby treats such string as literal, opposed to double-quotes)

To check if element is a member of an array you should use Array#include? so the code becomes

Rack::Attack.blacklist('allow from localhost') do |req|
  !a.include? req.ip
end

I know it's too late but I didn't like the Array#include? solution so I went ahead and added 2 new methods for safelist and blocklist each to have support for the same. Sharing it here as it will help other users too. It can be found in forked rack_attack branch.

Usage:

Safelisting:

# config/initializers/rack_attack.rb (for rails app)

ALLOWED_IPS = %w[127.0.0.1 ::1 5.6.7.8 123.456.789.0/24]

Rack::Attack.safelist_ips(ALLOWED_IPS)

Blocklisting:

# config/initializers/rack_attack.rb (for rails apps)

BLOCKED_IPS = %w[1.2.3.4 123.456.789.0/24]

Rack::Attack.blocklist_ips(BLOCKED_IPS)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!