1

私は単純なイントラネット アプリケーションに取り組んでいます。一部のユーザーはいますが、一般スタッフがログインする必要はありません。どのコンピュータからでもイントラネットにアクセスし、ログインせずに必要なものにアクセスできる必要があります。

多くのユーザーはリモートであり、同じ方法で対話できる必要があります。

私が達成しようとしているのは次のとおりです。ログインせずにルート URL に直接アクセスする 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

これを達成する方法についての指針をいただければ幸いです。ありがとう!

4

1 に答える 1

3

From:Rails3-ルート経由のIPのホワイトリストリスト

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ステートメントにを追加できます。または、Deviseを使用している場合は、これを次のように追加します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
于 2012-10-21T13:43:44.450 に答える