我对Rails安全性和使用Security on Rails的主题感兴趣。我正在实施RBAC /第142页/我无法通过主题中的错误。 这是代码:
module RoleBasedControllerAuthorization
def self.included(base)
base.extend(AuthorizationClassMethods)
end
def authorization_filter
user = User.find(:first,
:conditions => ["id = ?", session[:user_id]])
action_name = request.parameters[:action].to_sym
action_roles = self.class.access_list[action_name]
if action_roles.nil?
logger.error "You must provide a roles declaration\
or add skip_before_filter :authorization_filter to\
the beginning of #{self}."
redirect_to :controller => 'root', :action => 'index'
return false
elsif action_roles.include? user.role.name.to_sym
return true
else
logger.info "#{user.user_name} (role: #{user.role.name}) attempted to access\
#{self.class}##{action_name} without the proper permissions."
flash[:notice] = "Not authorized!"
redirect_to :controller => 'root', :action => 'index'
return false
end
end
end
module AuthorizationClassMethods
def self.extended(base)
class << base
@access_list = {}
attr_reader :access_list
end
end
def roles(*roles)
@roles = roles
end
def method_added(method)
logger.debug "#{caller[0].inspect}"
logger.debug "#{method.inspect}"
@access_list[method] = @roles
end
end
并且@access_list [method] = @roles行抛出异常:
ActionController::RoutingError (You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]=):
app/security/role_based_controller_authorization.rb:66:in `method_added'
app/controllers/application_controller.rb:5:in `<class:ApplicationController>'
app/controllers/application_controller.rb:1:in `<top (required)>'
app/controllers/home_controller.rb:1:in `<top (required)>'
我正在使用Rails 3.0.3和Ruby 1.9.2。我在数据库中存储会话。最后,谢谢你的每一个建议。
答案 0 :(得分:0)
您似乎无法访问@access_list
中的method_added
。我会试试
class << base
attr_accessor :access_list
@access_list = {}
end
可能无法解决您的特定问题,但如果您的access_list属性为只读,则无法拨打@access_list[method] = @roles
。
答案 1 :(得分:0)
我不确定这是不是问题,但这看起来很可疑:
class << base
@access_list = {}
attr_reader :access_list
end
@access_list
不应该是类变量@@access_list
吗?
答案 2 :(得分:0)
您将@access_list
定义为类的实例变量,但您将其作为类的实例的instance_variable访问。以下应该可行:
module AuthorizationClassMethods
def access_list
@access_list ||={}
end
def method_added(method)
logger.debug "#{caller[0].inspect}"
logger.debug "#{method.inspect}"
access_list[method] = @roles
end
end
如果你需要Auhorization,你可能想看看Ryan Bates的Cancan