Rails 3 - 通过路由将IP列入白名单

Sha*_*non 12 ip routing ruby-on-rails constraints

这是一个两部分问题.我需要将我在开发服务器上的rails网站限制为只有几个IP地址,因此公众无法访问它.(基本HTTP身份验证不会"完全"工作,因为auth会破坏项目中的Flash上​​传器.)

基于我的Google搜索,这是我在路线文件中提出的...

class WhitelistConstraint
  def initialize
    @ips = '127.0.0.1'
  end

  def matches?(request)
    @ips.include?(request.remote_ip)
  end
end

MyProject::Application.routes.draw do
  constraints WhitelistConstraint.new do
     # all my routing stuff here
  end
end
Run Code Online (Sandbox Code Playgroud)

工作得很好.但是,我需要修改它以便使用多个IP地址.我尝试在@ips上使用数组,以及循环遍历每个循环,但都没有工作.

最重要的是,我的问题的第二部分......我可能只需要检查IP的一部分,例如'127.0.0'.我该怎么办?

Far*_*gam 25

我不知道,你可以通过途径做到这一点,我的做法是只拥有before_filterApplicationController,只是有东西做:

before_filter :protect

def protect
  @ips = ['127.0.0.1', '203.123.10.1'] #And so on ...]
  if not @ips.include? request.remote_ip
     # Check for your subnet stuff here, for example
     # if not request.remote_ip.include?('127.0,0')
     render :text => "You are unauthorized"
     return
  end
end
Run Code Online (Sandbox Code Playgroud)


Doo*_*oon 8

那么使用NetAddr :: CIDR呢?

这样的事情?

class WhitelistConstraint
  def initialize
    @ips = []
    @ips << NetAddr::CIDR.create('127.0.0.0/8')
    @ips << NetAddr::CIDR.create('192.168.0.0/16')
  end

  def matches?(request)
    valid = @ips.select {|cidr| cidr.contains?(request.remote_ip) }
    !valid.empty?
   end
 end

 MyProject::Application.routes.draw do
    constraints WhitelistConstraint.new do
     # all my routing stuff here
     end
 end 
Run Code Online (Sandbox Code Playgroud)

这样,您可以指定应列入白名单的IP块,而不必担心部分匹配?

>> require 'netaddr'
=> true
>> @ips = []
=> []
>> @ips << NetAddr::CIDR.create('127.0.0.0/8')
=> [127.0.0.08]
>> @ips << NetAddr::CIDR.create('192.168.0.0/16')
=> [127.0.0.08, 192.168.0.016]
>> @ips.select { |c| c.contains? '192.168.10.1' }
=> [192.168.0.016]
>> @ips.select { |c| c.contains? '192.169.10.1' }
=> []
Run Code Online (Sandbox Code Playgroud)