2011-04-05 30 views
12

這是一個兩部分問題。我需要將我在開發服務器上投放的rails網站限制爲只有幾個IP地址,因此公衆無法訪問它。 (基本的HTTP驗證並不完全正常,因爲驗證會破壞項目中的Flash上​​傳器。)Rails 3 - 通過路由將白名單IP列入清單

基於我谷歌搜索的內容,這是我在我的路由文件中提出的。 。

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 

工程很不錯。但是,我需要修改這個以便使用多個IP地址。我嘗試在@ips上使用數組,以及循環遍歷每個循環,但都無效。

最重要的是,我的問題的第二部分...我可能只需要檢查一段IP,如'127.0.0'。我會怎麼做?

回答

25

我不知道,你可以通過途徑做到這一點,我的辦法是隻在一個ApplicationControllerbefore_filter只是有東西做:關於使用NetAddr::CIDR

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 
+0

我沒你也知道你也可以。然而,這個解決方案對我來說很有效,可能是更好的路線。可以看到它是從開發到生產(暫時是臨時服務器)的問題,但它只是暫時的,我可以根據需要在兩個環境中添加IP。謝謝。 – Shannon 2011-04-05 15:45:26

+0

你可以使用'Rails.env.production?'和'Rails.env.development?'來檢查某種'if'結構中的環境,以適合你需要做的任何事情。祝你好運:) – 2011-04-05 15:49:45

+0

這個解決方案適用於IP範圍嗎? – DanielCW 2012-08-29 16:18:17

7

什麼?

和類似的東西?

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 

這樣,您可以指定應列入白名單的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' } 
=> [] 
+0

沒有爲我工作,得到'未初始化的常量WhitelistConstraint :: NetAddr'錯誤 – Shannon 2011-04-05 15:44:10

+0

如果使用rails 3並且執行捆綁舞蹈,您需要將NetAddr Gem添加到您的Gemfile中:)或者更新您的gem config,如果在rails 2上。 – Doon 2011-04-05 16:42:41

+0

啊好的,這是有道理的。找到上面的替代解決方案,可能更好,因爲這只是一個「臨時」的內部測試的東西,但如果我需要的東西,我會記住上述更復雜 – Shannon 2011-04-05 16:51:20

1

或者乾脆使用Apache的.htaccess:

  1. 添加以下到的http.conf或任何的conf文件,你有Apache和

的AllowOverride所有的Rails應用程序

  1. 創建文件的.htaccess在軌文件夾,並添加以下
Allow from xxx.xxx.xxx.xxx 
Deny from all 
+0

曾經嘗試過,但沒有成功,它正在研究rails .htaccess,有人建議使用路由,這就是但是,現在你提到它了,我可能沒有在我的http.conf中使用AllowOverride。 – Shannon 2011-04-05 15:43:32

+0

它是如何工作的? – 2011-04-06 18:32:51

+0

我還沒來得及嘗試一下,因爲我使用了另一種解決方案,但是項目中會有一個需要使用.htaccess文件的地方,所以這會很方便。 – Shannon 2011-04-08 13:44:01

1

也可以包圍,象這樣一個範圍路線聲明:

scope :constraints => lambda{|req|%w(127.0.0.1).include? req.remote_addr} do 

    ... your beautiful routes 

end