Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: possible to restrict a route based on IP address (or range?)

I know this usually happens in the controller but I'm wondering if it's possible in config/routes.rb to restrict a route based on a specific IP (or range of IPs)? Sort of a whitelist, of sorts.

for example I'd like to restrict this route to only IPs on our subnet:

#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
like image 638
Meltemi Avatar asked Nov 01 '25 07:11

Meltemi


1 Answers

Based on the example from the Rails Docs you could do:

#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 goes into more detail on constraints and how to use them.

like image 126
clang1234 Avatar answered Nov 03 '25 22:11

clang1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!