Restrict access by IP address

I’d like to restrict access to some controllers of my app to certain IP
addresses only, but can’t find any information on this. Can anyone
suggest a good way to go about this?
All I could think of was adding a entry to public/.htaccess,
but that appears not to work.

I’d like to restrict access to some controllers of my app to certain IP
addresses only, but can’t find any information on this. Can anyone
suggest a good way to go about this?
All I could think of was adding a entry to public/.htaccess,
but that appears not to work.

You could write a before_filter for those controllers and check the
environment hash for the IP and if it doesn’t match return false.

Philip H. wrote:

You could write a before_filter for those controllers and check the
environment hash for the IP and if it doesn’t match return false.

Thanks. I have tried a simple one like this:

if request.remote_ip !~ /^XXX.YYY.ZZZ./
redirect_to ‘/’
flash.now[:notice] = “Access denied!”
return false
end

That seems to work, but I wondered if there might be another way. If
this is the accepted method then that’s OK, though.

In the main application controller, we read a small text file
containing IP addresses then set a flag if the current IP address
matches anything in the file:

not the best code, but it works:

begin

@ipflag = false
File.open(RAILS_ROOT + ‘/config/iplist.txt’, ‘r’).each do |line|
@ipflag = true if request.remote_addr.to_str == ip.strip.to_str
end

end

then in your controlles use @ipflag appropriately.

No doubt you could also check for partial addresses with a regex to
deal with parts of a class. As I said not the most complete thing, but
something similar to the above works for us to block whatever
miscreants we need to :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs