Search code examples
ruby-on-railsrubyauthenticationpasswordswhitelist

Restrict access to app by ip address OR via password (rails app)


I have the whitelabel working as follows in my application controller:

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

I'd like to add the option that IF your IP is not whitelisted, you can enter a password to see the page.

There is no user model on this application (we only use it to display company metrics at the office (one page view) and want to be able to access the site at home/on mobile without having to constantly update ip's)

Thanks for any help


Solution

  • You can use the basic authentication, like below for your case:

    def protect
      @ips = ['127.0.0.1', '203.123.10.1'] #And so on ...]
      if not @ips.include? request.remote_ip
         if user = authenticate_with_http_basic { |u, p| u=='username' and p=='secret' }
              @current_user = user
         else
              request_http_basic_authentication
         end
      end
    end