2012-10-21 81 views
1

我在一個簡單的Intranet應用工作,雖然有一些用戶,對普通員工登錄沒有要求。他們應該能夠從任何計算機訪問內網和訪問他們需要的東西無需登錄。Rails路由和身份驗證?

我們的許多用戶是遠程的,他們應該能夠以同樣的方式進行交互。

我想實現如下; &子網直行到根網址無需登錄(管理員仍然可以登錄)的IP地址列表。任何訪客不列入白名單的IP列表上&子網應該看到靜態拒絕訪問頁面。在那個頁面上應該是一個登錄鏈接。登錄後,他們可以與內聯網只是因爲他們可以,如果他們在我們的白名單中的子網進行交互。一旦他們註銷,他們會再次看到拒絕訪問頁面。

我有下面的代碼在我的應用程序控制器:

class ApplicationController < ActionController::Base 
    before_filter :protect 
    protect_from_forgery 
    private 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    rescue ActiveRecord::RecordNotFound 
    end 

    helper_method :current_user 

    def authorized? 
    not current_user.nil? 
    end 

    def authorize 
    redirect_to login_url, alert: "Not authorized" unless authorized? 
    end 

    def authorize_admin 
    redirect_to login_url, alert: "Not authorized" unless authorized? && current_user.admin? 
    end 

    def protect 
    @ips = ['127.0.0.1','123.123.123.12','192.168.5.0/24'] 
    allowed = false 
     bremote_ip = 0 
     request.remote_ip.split('.').each { |x| bremote_ip = (bremote_ip << 8) + x.to_i } 
     @ips.each do |ipstring| 
     ip, mask = ipstring.split '/' 
     mask = mask ? mask.to_i : 32 
     bip = 0 
     ip.split('.').each { |x| bip = (bip << 8) + x.to_i } 
     bmask = ((1 << mask) - 1) << (32 - mask) 
     if bip & bmask == bremote_ip & bmask 
      allowed = true 
      break 
     end 
    end 

    if not allowed 
     render :template => "static/protect", :layout => "static" 
     return 
    end 
    end 

end 

就如何實現這一目標的任何指針將不勝感激。謝謝!

回答

3

來源:Rails 3 - Whitelisting list of IPs via routes

使用netaddr寶石:

before_filter :protect 

def protect 
     @ips = [] 
     @ips << NetAddr::CIDR.create('127.0.0.0/8') 
     @ips << NetAddr::CIDR.create('192.168.5.0/24') 
     @ips << NetAddr::CIDR.create('123.123.123.12') 
     valid = @ips.select {|cidr| cidr.contains?(request.remote_ip) } 
     if valid.empty? and !authorized? 
     authorize 
     return 
     end 
end 

編輯

在這種情況下,以上只是示例跳過靜態保護頁面,將用戶重定向到登錄頁。我不明白需要一箇中間靜態頁面?

注意:爲避免「太多重定向」錯誤,您可以將:except添加到before_filter語句中。或者,如果你使用的設計,您添加到config/application.rb

# In config/application.rb 
module YourAppNameHere 
    class Application < Rails::Application 
    # Whatever else is already here... 

    # The part to add 
    config.to_prepare do 
     Devise::SessionsController.skip_before_filter :protect 
    end 
    end 
end 
+0

除非我失去了一些東西,那不是重複,我已經相同的功能?阻止任何不在白名單上的人,但不允許任何不在白名單上的人訪問 - 即使他們登錄了? – dannymcc

+0

@dannymcc對不起 - 我不明白你的主要問題是什麼。上面更新。 – mccannf

+0

你當然是對的。靜態頁面令人困惑。我基本上希望不在白名單上的任何人都必須登錄查看任何內容,而白名單上的用戶應該看到任何不需要驗證的內容。 – dannymcc