How can I restrict access to ALL devise controllers by IP address'?

512 views
Skip to first unread message

Christian Fazzini

unread,
Jun 22, 2011, 11:22:31 PM6/22/11
to Devise
How can I restrict access to ALL devise controllers by IP address'? I
am trying to allow only users from a specific IP address to view the
admin interface / pages.

I found this approach. Which is to include a restrict_access method in
the before filter. However, its a bit repetitive if I have to copy
this method on all the Devise controllers that I currently use. Is
there a better approach?

class Admin::SessionsController < Devise::SessionsController

before_filter :restrict_access

# Needed to restrict access to a set of IP's only. We don't want
random users trying to access the admin interface
def restrict_access
if Rails.env == 'development' or Rails.env == 'test'
whitelist = ['59.120.201.20', '59.120.201.21'].freeze
else
whitelist = ['59.120.201.20', '59.120.201.21'].freeze
end

unless whitelist.include? request.remote_ip
redirect_to root_path, :notice => 'Access denied!'
end
end
...

kadoudal

unread,
Jun 23, 2011, 10:58:59 AM6/23/11
to Devise
why don't you use a constraint on routing ? ( got it from some
example...)

in route.rb

at the beginning of your routes.rb you write
class BlacklistConstraint
def initialize
@ips = Blacklist.retrieve_ips
end

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

then later you blacklist or whitelist

match "/some_route" => "blacklist#index", :constraints =>
BlacklistConstraint.new

look at the Rails routing doc...

On Jun 23, 5:22 am, Christian Fazzini <christian.fazz...@gmail.com>
wrote:

Christian Fazzini

unread,
Jun 25, 2011, 11:59:03 PM6/25/11
to Devise
Thanks for that response! Exactly what I was looking for.
Reply all
Reply to author
Forward
0 new messages