Ruby on rails 3 如何通过IP地址限制对所有Desive控制器的访问;?
如何通过IP地址限制对所有Desive控制器的访问?我试图只允许特定IP地址的用户查看管理界面/页面 我找到了这种方法。这将在before筛选器中包含一个restrict_访问方法。然而,如果我必须在我目前使用的所有Desive控制器上复制此方法,则会有点重复 有更好的方法吗Ruby on rails 3 如何通过IP地址限制对所有Desive控制器的访问;?,ruby-on-rails-3,devise,Ruby On Rails 3,Devise,如何通过IP地址限制对所有Desive控制器的访问?我试图只允许特定IP地址的用户查看管理界面/页面 我找到了这种方法。这将在before筛选器中包含一个restrict_访问方法。然而,如果我必须在我目前使用的所有Desive控制器上复制此方法,则会有点重复 有更好的方法吗 class Admin::SessionsController < Devise::SessionsController before_filter :restrict_access # Needed t
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
...
class Admin::sessioncontroller“拒绝访问!”
结束
结束
...
我相信所有Desive控制器都扩展了您的应用程序控制器,因此您可以将该方法作为受保护的方法放在ApplicationController中,然后只需调用
before_filter :restrict_access
在每个装置控制器上 构建一个如下所示的类,并将其放置在
RAILS\u ROOT/lib/blacklist\u constraint.rb
中
class BlacklistConstraint
def initialize
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
end
def matches?(request)
!@whitelist.include?(request.remote_ip)
end
end
。。。在routes.rb文件中
match "*", :constraints => BlacklistConstraint.new, :controller => "blacklist", :action => "my_access_denied_action"
您可能需要在初始值设定项中加载该类,或者在config/application.rb
(Rails3.x)中修改config.autoload\u路径+=%W({Rails.root}/lib)