Rails:可以根据IP地址(或范围?)限制路由

时间:2013-02-07 18:59:39

标签: ruby-on-rails routing routes sidekiq

我知道这通常发生在控制器中,但我想知道config/routes.rb是否可以根据特定IP(或IP范围)限制路由?排序的白名单。

例如,我想将此路由限制为仅在我们子网上的IP:

#config/routes.rb
require 'sidekiq/web'

MyApp::Application.routes.draw do
  resources :users
  ...
  mount Sidekiq::Web, at: "/sidekiq"      # <== restrict this based on IP address
  ...
end

1 个答案:

答案 0 :(得分:4)

基于您可以执行的Rails Docs示例:

#config/routes.rb
require 'sidekiq/web'

MyApp::Application.routes.draw do
  resources :users
  ...
  mount Sidekiq::Web, at: "/sidekiq", :constraint => Whitelist.new
  ...
end

class Whitelist
  def initialize
    @ips = Whitelist.retrieve_ips
  end

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

  def retrieve_ips
    # get and return your whitelist of ips
  end
end

This post by Yehuda Katz详细介绍了约束以及如何使用它们。